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();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = api.registerInterceptTokenManager(signOut);
|
||||
|
||||
return () => {
|
||||
subscription();
|
||||
};
|
||||
}, [signOut]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ user, signIn, signOut, updateUserData, isLoadingUserStorageData }}>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import axios from 'axios';
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
|
||||
import { AppError } from '@utils/AppError';
|
||||
|
||||
type SignOut = () => void;
|
||||
type APIInstanceProps = AxiosInstance & {
|
||||
registerInterceptTokenManager: (signOut: SignOut) => () => void;
|
||||
};
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: 'http://192.168.0.61:3333',
|
||||
});
|
||||
}) as APIInstanceProps;
|
||||
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
|
|
@ -15,7 +20,8 @@ api.interceptors.request.use(
|
|||
},
|
||||
);
|
||||
|
||||
api.interceptors.response.use(
|
||||
api.registerInterceptTokenManager = (signOut: SignOut) => {
|
||||
const interceptTokenManager = api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response && error.response.data) {
|
||||
|
|
@ -23,6 +29,11 @@ api.interceptors.response.use(
|
|||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
return () => {
|
||||
api.interceptors.response.eject(interceptTokenManager);
|
||||
};
|
||||
};
|
||||
|
||||
export { api };
|
||||
|
|
|
|||
Loading…
Reference in a new issue