Files
parcer/src/context/auth.tsx

104 lines
2.9 KiB
TypeScript
Raw Normal View History

2024-09-24 12:07:32 +05:30
import { useReducer, createContext, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
interface ProviderProps {
2024-09-24 12:10:04 +05:30
children: React.ReactNode;
2024-09-24 12:07:32 +05:30
}
2024-09-24 12:08:19 +05:30
interface ActionType {
type: 'LOGIN' | 'LOGOUT';
payload?: any;
2024-09-24 12:10:04 +05:30
}
2024-09-24 12:08:19 +05:30
2024-09-24 12:07:32 +05:30
type InitialStateType = {
2024-09-24 12:10:04 +05:30
user: any;
2024-09-24 12:07:32 +05:30
};
const initialState = {
2024-09-24 12:10:04 +05:30
user: null,
2024-09-24 12:07:32 +05:30
};
const Context = createContext<{
2024-09-24 12:10:04 +05:30
state: InitialStateType;
dispatch: any;
2024-09-24 12:07:32 +05:30
}>({
2024-09-24 12:10:04 +05:30
state: initialState,
dispatch: () => null,
2024-09-24 12:07:32 +05:30
});
2024-09-24 12:08:19 +05:30
const reducer = (state: InitialStateType, action: ActionType) => {
2024-09-24 12:10:04 +05:30
switch (action.type) {
case 'LOGIN':
return {
...state,
user: action.payload,
};
case 'LOGOUT':
return {
...state,
user: null,
};
default:
return state;
}
2024-09-24 12:07:32 +05:30
};
const Provider = ({ children }: ProviderProps) => {
2024-09-24 12:10:04 +05:30
const [state, dispatch] = useReducer(reducer, initialState);
2024-09-24 12:07:32 +05:30
2024-09-24 12:10:04 +05:30
const navigate = useNavigate();
2024-09-24 12:07:32 +05:30
2024-09-24 12:10:04 +05:30
// get user info from local storage
useEffect(() => {
dispatch({
type: 'LOGIN',
payload: JSON.parse(window.localStorage.getItem('user') || 'null'),
2024-09-24 12:07:32 +05:30
});
2024-09-24 12:10:04 +05:30
}, []);
axios.interceptors.response.use(
function (response) {
// any status code that lies within the range of 2XX causes this function to trigger
return response;
},
function (error) {
// any status codes that fall outside the range of 2XX cause this function to trigger
let res = error.response;
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
return new Promise((resolve, reject) => {
axios
2024-09-24 12:31:57 +05:30
.get('http://localhost:8080/auth/logout')
2024-09-24 12:10:04 +05:30
.then((data) => {
console.log('/401 error > logout');
dispatch({ type: 'LOGOUT' });
window.localStorage.removeItem('user');
navigate('/login'); // Replace router.push with navigate
})
.catch((err) => {
console.log('AXIOS INTERCEPTORS ERROR:', err);
reject(error);
});
});
}
return Promise.reject(error);
}
);
// csrf - include tokens in the axios header every time a request is made
useEffect(() => {
const getCsrfToken = async () => {
2024-09-24 12:31:57 +05:30
const { data } = await axios.get('http://localhost:8080/csrf-token');
2024-09-24 12:10:04 +05:30
console.log('CSRFFFFF =>>>>', data);
(axios.defaults.headers as any)['X-CSRF-TOKEN'] = data.getCsrfToken;
};
getCsrfToken();
}, []);
2024-09-24 12:07:32 +05:30
2024-09-24 12:10:04 +05:30
return (
<Context.Provider value={{ state, dispatch }}>{children}</Context.Provider>
);
2024-09-24 12:07:32 +05:30
};
export { Context, Provider };