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);
}
);
Follow official document: Navigating without the navigation prop
try something like this
// App.js
import { createStackNavigator, createAppContainer } from 'react-navigation';
import NavigationService from './NavigationService';
const TopLevelNavigator = createStackNavigator({ /* ... */ })
const AppContainer = createAppContainer(TopLevelNavigator);
export default class App extends React.Component {
// ...
render() {
return (
<AppContainer
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
);
}
}
// NavigationService.js
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
};
No , you dont need Redux for this. if you are using React Navigation you can do like this way. you can access from everywhere
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With