Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to screen from an api interceptor (outside of component) in React Native

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);
  }
);
like image 520
Haris Bouchlis Avatar asked Jan 17 '19 08:01

Haris Bouchlis


2 Answers

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,
};
like image 164
Olivia Tree Avatar answered Sep 29 '22 07:09

Olivia Tree


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

like image 35
Nazır Dogan Avatar answered Sep 29 '22 07:09

Nazır Dogan