Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - logout/redirect user on failed api call

I built a web app using Reactjs. I used router and redux for state management for authentication. Everything works fine BUT the problem is with api calls. After the user logged in and calls a ... service I want to check the response of the service wether it contains any token problem (example: token expired). If there is a token problem I want to invalidate the token (remove it) and sent the user back to the login page with an error message. Now, I can do this if I do all api calls inside my redux action/reducer. But I'm not sure if I have to implement redux for every call because I don't need the data in other components. And also implementing all services in redux is time consuming and needs a lot of code.

I replicated the project to stackblitz.

https://stackblitz.com/edit/react-auth?file=index.js

Scenario is simple. Click on login and your are in the app. The app automatically calls a service and gets a response. If you change the URL to a faulty one inside api.js then this service will give a '40x' response. When I receive this response I want to redirect the user to the Login page.

Any help/suggestions?

Thanks.

like image 987
shotofcode Avatar asked Jul 12 '18 10:07

shotofcode


1 Answers

Here is an example using axios and your api.js :

import axios from 'axios';

const apiKey = 'API_KEY';

export async function getWeather() {
  const url = `https://reqres.in/api/users?page=2`;
  axios.interceptors.response.use(handleSuccess, handleError)
  return await axios.post(url);
 }

function handleSuccess(response) {
  console.log('success');
  return ({data: response.data});
}

function handleError(error) {
  if (error.message === 'Network Error') {
     // The user doesn't have internet
      return Promise.reject(error);
   }
   switch (error.response.status) {
      case 400:
        break;
      case 401:
        // Go to login
        break;
      case 404:
        // Show 404 page
        break;
      case 500:
        // Serveur Error redirect to 500
        break;
      default:
        // Unknow Error
       break;
    }
    return Promise.reject(error);
}

So depending on the code status and the behavior you want for the code answer you should redirect the user or just show a modal to him.

Check the doc on axios interceptors

like image 86
Pintouch Avatar answered Oct 17 '22 02:10

Pintouch