shotofcode
shotofcode

Reputation: 497

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.

Upvotes: 6

Views: 6177

Answers (2)

Guzman90
Guzman90

Reputation: 87

I know this old but I'm trying to do the same than shotofcode but with fetch and without redux (basically because I don't need it anywhere else). I was able to redirect to the login page from the service when my server response with "401 Unauthorized" but I'm unable to return an error message from there.

A possible solution I can think of is saving the error message in localStorage and get it in the login page.Another option is catch and handle the error at component level but defeat the purpose of using a service and implicates repeating a lot of code.

Did anyone find a better solution?

Upvotes: 0

Pintouch
Pintouch

Reputation: 2619

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

Upvotes: 6

Related Questions