feat: pass signOut function to api interceptor
So it can logout the user when the token expires and refresh token fails
This commit is contained in:
parent
268b5ab43e
commit
67bc310158
2 changed files with 30 additions and 11 deletions
|
|
@ -102,6 +102,14 @@ export function AuthContextProvider({ children }: AuthContextProviderProps) {
|
||||||
loadUserData();
|
loadUserData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const subscription = api.registerInterceptTokenManager(signOut);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
subscription();
|
||||||
|
};
|
||||||
|
}, [signOut]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
value={{ user, signIn, signOut, updateUserData, isLoadingUserStorageData }}>
|
value={{ user, signIn, signOut, updateUserData, isLoadingUserStorageData }}>
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,15 @@
|
||||||
import axios from 'axios';
|
import axios, { AxiosInstance } from 'axios';
|
||||||
|
|
||||||
import { AppError } from '@utils/AppError';
|
import { AppError } from '@utils/AppError';
|
||||||
|
|
||||||
|
type SignOut = () => void;
|
||||||
|
type APIInstanceProps = AxiosInstance & {
|
||||||
|
registerInterceptTokenManager: (signOut: SignOut) => () => void;
|
||||||
|
};
|
||||||
|
|
||||||
const api = axios.create({
|
const api = axios.create({
|
||||||
baseURL: 'http://192.168.0.61:3333',
|
baseURL: 'http://192.168.0.61:3333',
|
||||||
});
|
}) as APIInstanceProps;
|
||||||
|
|
||||||
api.interceptors.request.use(
|
api.interceptors.request.use(
|
||||||
(config) => {
|
(config) => {
|
||||||
|
|
@ -15,14 +20,20 @@ api.interceptors.request.use(
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
api.interceptors.response.use(
|
api.registerInterceptTokenManager = (signOut: SignOut) => {
|
||||||
(response) => response,
|
const interceptTokenManager = api.interceptors.response.use(
|
||||||
(error) => {
|
(response) => response,
|
||||||
if (error.response && error.response.data) {
|
(error) => {
|
||||||
return Promise.reject(new AppError(error.response.data.message));
|
if (error.response && error.response.data) {
|
||||||
}
|
return Promise.reject(new AppError(error.response.data.message));
|
||||||
return Promise.reject(error);
|
}
|
||||||
},
|
return Promise.reject(error);
|
||||||
);
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
api.interceptors.response.eject(interceptTokenManager);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export { api };
|
export { api };
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue