Categories
React Answers

How to handle 401 error in Axios and React?

Spread the love

Sometimes, we want to handle 401 error in Axios and React.

In this article, we’ll look at how to handle 401 error in Axios and React.

How to handle 401 error in Axios and React?

To handle 401 error in Axios and React, we can add a response interceptor.

For instance, we write

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      // ...
    }
    return error;
  }
);

to call axios.interceptors.response.use with a function that runs when we get a response and a function that runs when we get an error respectively.

In the error handling function, we get the response status code with error.response.status.

If it’s 401, then we do some thing with the response.

Conclusion

To handle 401 error in Axios and React, we can add a response interceptor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *