I am working on a React Native application that authenticates requests with JWT tokens. For this purpose i have created axios request and response interceptors to add the token to each request (request interceptor) and redirect the user to the login screen whenever a response has 401 HTTP status (response interceptor).
The problem is that i haven't found a way to do the redirect outside of a component. The code below is in an API service that is imported whenever i want an API call to be made.
What do i need to do to redirect to my login screen since this service is stateless and doesn't care what component it is called from?
// Response interceptor
axiosInstance.interceptors.response.use(
response => {
// Do something with response data
if (response.status === 401) {
deviceStorage.removeData('token');
// TODO:
// Redirect to login page
}
return response;
},
error => {
// Do something with response error
return Promise.reject(error);
}
);