Handle 401 error in react-redux app using apisauce

428 Views Asked by At

The problem: i have many sagas that do not handle an 401 error in response status, and now i have to deal with it. I have apiservice based on apisause and i can write an response monitor with it to handle 401 error (like interceptors in axios). But i cant dispatch any action to store to reset user data, for example, because there is no store context in apiservice. How to use dispatch function in apiservice layer? Or use put() function in every saga when i recieve 401 response status is the only right way?

1

There are 1 best solutions below

0
On

you can use refs for using navigation in 'apisauce' interceptors this is my code and it works for me ;)

-- packages versions
@react-navigation/native: ^6.0.6
@react-navigation/native-stack: ^6.2.5
apisauce: ^2.1.1
react: 17.0.2
react-native: ^0.66.3

I have a main file for create apisauce

// file _api.js :

export const baseURL = 'APP_BASE_URL';
import { create } from 'apisauce'
import { setAPIInterceptors } from './interceptors';

const APIClient = create({ baseURL: baseURL })
setAPIInterceptors(APIClient)

and is file interceptors.js I'm watching on responses and manage them:

// file interceptors.js

import { logout } from "../redux/actions";
import { store } from '../redux/store';
import AsyncStorage from '@react-native-async-storage/async-storage';
    
export const setAPIInterceptors = (APIClient) => {  
        APIClient.addMonitor(monitor => {
            // ...
            // error Unauthorized
            if(monitor.status === 401) {
                store.dispatch(logout())
                AsyncStorage.clear().then((res) => {
                    RootNavigation.navigate('login');
                })
            }
    
        })
    }

then I create another file and named to 'RootNavigation.js' and create a ref from react-native-navigation:

// file RootNavigation.js

import { createNavigationContainerRef } from '@react-navigation/native';

export const navigationRef = createNavigationContainerRef()

export function navigate(name, params) {
  if (navigationRef.isReady()) {
    navigationRef.replace(name, params);
  }
}
// add other navigation functions that you need and export them

then you should to set some changes in you App.js file:

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

finally in anywhere you can call this function for use react native navigations

full focument is in here that explain how to Navigating without the navigation prop

Navigating without the navigation prop