feat: proper retrieval of user from local storage
This commit is contained in:
@@ -21,7 +21,7 @@ const initialState = {
|
|||||||
|
|
||||||
const AuthContext = createContext<{
|
const AuthContext = createContext<{
|
||||||
state: InitialStateType;
|
state: InitialStateType;
|
||||||
dispatch: any;
|
dispatch: React.Dispatch<ActionType>;
|
||||||
}>({
|
}>({
|
||||||
state: initialState,
|
state: initialState,
|
||||||
dispatch: () => null,
|
dispatch: () => null,
|
||||||
@@ -46,38 +46,34 @@ const reducer = (state: InitialStateType, action: ActionType) => {
|
|||||||
|
|
||||||
const AuthProvider = ({ children }: AuthProviderProps) => {
|
const AuthProvider = ({ children }: AuthProviderProps) => {
|
||||||
const [state, dispatch] = useReducer(reducer, initialState);
|
const [state, dispatch] = useReducer(reducer, initialState);
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
axios.defaults.withCredentials = true;
|
axios.defaults.withCredentials = true;
|
||||||
|
|
||||||
// get user info from local storage
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch({
|
const storedUser = window.localStorage.getItem('user');
|
||||||
type: 'LOGIN',
|
if (storedUser) {
|
||||||
payload: JSON.parse(window.localStorage.getItem('user') || 'null'),
|
dispatch({ type: 'LOGIN', payload: JSON.parse(storedUser) });
|
||||||
});
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
axios.interceptors.response.use(
|
axios.interceptors.response.use(
|
||||||
function (response) {
|
function (response) {
|
||||||
// any status code that lies within the range of 2XX causes this function to trigger
|
|
||||||
return response;
|
return response;
|
||||||
},
|
},
|
||||||
function (error) {
|
function (error) {
|
||||||
// any status codes that fall outside the range of 2XX cause this function to trigger
|
const res = error.response;
|
||||||
let res = error.response;
|
|
||||||
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
|
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
axios
|
axios
|
||||||
.get('http://localhost:8080/auth/logout')
|
.get('http://localhost:8080/auth/logout')
|
||||||
.then((data) => {
|
.then(() => {
|
||||||
console.log('/401 error > logout');
|
console.log('/401 error > logout');
|
||||||
dispatch({ type: 'LOGOUT' });
|
dispatch({ type: 'LOGOUT' });
|
||||||
window.localStorage.removeItem('user');
|
window.localStorage.removeItem('user');
|
||||||
navigate('/login'); // Replace router.push with navigate
|
navigate('/login');
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.log('AXIOS INTERCEPTORS ERROR:', err);
|
console.error('AXIOS INTERCEPTORS ERROR:', err);
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -86,16 +82,12 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// csrf - include tokens in the axios header every time a request is made
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getCsrfToken = async () => {
|
const getCsrfToken = async () => {
|
||||||
try {
|
try {
|
||||||
const { data } = await axios.get('http://localhost:8080/csrf-token');
|
const { data } = await axios.get('http://localhost:8080/csrf-token');
|
||||||
console.log('CSRF Token Response:', data);
|
if (data.csrfToken) {
|
||||||
if (data && data.csrfToken) {
|
|
||||||
(axios.defaults.headers as any)['X-CSRF-TOKEN'] = data.csrfToken;
|
(axios.defaults.headers as any)['X-CSRF-TOKEN'] = data.csrfToken;
|
||||||
} else {
|
|
||||||
console.error('CSRF token not found in the response');
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching CSRF token:', error);
|
console.error('Error fetching CSRF token:', error);
|
||||||
@@ -105,8 +97,10 @@ const AuthProvider = ({ children }: AuthProviderProps) => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ state, dispatch }}>{children}</AuthContext.Provider>
|
<AuthContext.Provider value={{ state, dispatch }}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export { AuthContext, AuthProvider };
|
export { AuthContext, AuthProvider };
|
||||||
Reference in New Issue
Block a user