0

What is the best way to test whether an API has failed due to expiry of JWT token in React (create-react-app), Redux and Redux-Saga?

Currently I'm checking for the response's status code in the API function which looks like the following, (I've written this test at only 1 place):

} else if(response.status === 401) {
    return {"success" : false, "unauthenticated": true }
}

In sagas, I test it in the following manner:

else if(data.unauthenticated) {
    yield put({type: LOGOUT, message: "You are unauthenticated, Please login again!"});
}

The problem with the above approach is, I've to write the test in every saga at the end of API calls. I was thinking if it is possible to perform this test only at a single place much like the first code snippet. As I think writing same test at different places only increases boilerplate code which is not good if I have to scale the application.

So, any suggestions on how I should go about it?

subham
  • 33
  • 4

1 Answers1

2

You can always make a global interceptor for the axios instance.

axios.interceptors.response.use(
   (response) => response,
   (error) => {
      if (error.response.status === 401) {
         store.dispatch(
           { type: LOGOUT, message: "You are unauthenticated, Please login again!" },
         );
      }
   },
);

Note: Remember to import your store to be able to call dispatch.

kind user
  • 32,209
  • 6
  • 49
  • 63