Haris Bouchlis
Haris Bouchlis

Reputation: 2566

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);
  }
);

Upvotes: 8

Views: 5167

Answers (5)

Olivia Tree
Olivia Tree

Reputation: 76

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,
};

Upvotes: 5

amirhosein
amirhosein

Reputation: 921

you can use this way:

import Component_1 from 'PATH TO IT'
import Component_2 from 'PATH TO IT'

this.state = {   
        status: 1
    }


render(){
    if(this.state.status == 1){
          return( <Component_1 onChange={(value)=> this.setState({status: value}) }/> )//Point => A
    }else if(this.state.status == 2){ 
             return( <Component_2 /> )
    }

here we use two component as child of one parent,in Point A we pass a function to child (called props) that give us ability to change state of parent inside of child,based on our work,and when the state is changed component_1 will be unmounted and component_2 will be mount ( login page for example). in component_1 we can use that function in props to change page like this:

if (response.status === 401) {
  deviceStorage.removeData('token');
  // TODO:
  this.props.onChange(2) // here you can redirect to that component
}

Upvotes: 1

Nazır Dogan
Nazır Dogan

Reputation: 1588

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

Upvotes: 3

Tasos Kakouris
Tasos Kakouris

Reputation: 175

Here is a simple medium article that describe redux with redux saga. https://medium.com/@tkssharma/understanding-redux-react-in-easiest-way-part-1-81f3209fc0e5

Use redux-saga as middleware and make use generator function new feauture in es6

Upvotes: 2

Ioanna Papaplioura
Ioanna Papaplioura

Reputation: 21

For this functionality, I think that you need to use Redux

Upvotes: 2

Related Questions