Skip to content

Commit

Permalink
#11 Extend token refresh duration to 24 hours
Browse files Browse the repository at this point in the history
  • Loading branch information
SandraBergstrom committed Jun 21, 2023
1 parent c1dbd41 commit 5ef8706
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/api/axiosDefaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ import axios from "axios";

axios.defaults.baseURL = 'https://travel-tickr-api-e57198555b47.herokuapp.com/' //url to api
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data' // multipart necessary since we have both text and images
axios.defaults.withCredentials = true
axios.defaults.withCredentials = true

export const axiosReq = axios.create();
export const axiosRes = axios.create();
30 changes: 28 additions & 2 deletions src/contexts/CurrentUserContext.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { createContext, useContext, useEffect, useState } from "react";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import axios from "axios";
import { axiosRes } from "../api/axiosDefaults";
import { response } from "msw";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";

export const CurrentUserContext = createContext();
export const SetCurrentUserContext = createContext();
Expand All @@ -9,10 +12,11 @@ export const useSetCurrentUser = () => useContext(SetCurrentUserContext)

export const CurrentUserProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const history = useHistory()

const handleMount = async () => {
try {
const { data } = await axios.get("dj-rest-auth/user/");
const { data } = await axiosRes.get("dj-rest-auth/user/");
} catch (err) {
console.log(err);
}
Expand All @@ -22,6 +26,28 @@ export const CurrentUserProvider = ({ children }) => {
handleMount();
}, []);

useMemo(() => {
axiosRes.interceptors.response.use(
(response) => response,
async (err) => {
if (err.response?.status === 401){
try {
await axios.post('/dj-rest-auth/token/refresh/')
} catch (err) {
setCurrentUser(prevCurrentUser => {
if (prevCurrentUser) {
history.push('/login')
}
return null
})
}
return axios(err.config)
}
return Promise.reject(err)
}
)
})

return (
<CurrentUserContext.Provider value={currentUser}>
<SetCurrentUserContext.Provider value={setCurrentUser}>
Expand Down

0 comments on commit 5ef8706

Please sign in to comment.