0

I am creating an axios interceptor to catch application wide 500 errors and to display an error page.
I am new to React, this is on existing codebase by someone else.

The issue I am facing is that axios interceptor actually does working, but when I try to set the state to render a component it fails

this.setState({ userLoaded: true, serverError: true }); 

giving:

Exception has occurred. Error: this is undefined

In Routes.js we have this:

const Routes = observer(class Routes extends React.Component {
  state = { userLoaded: false, serverError: false, serverUnauthorized: false };

  componentDidMount() {
    getMe().then(data => {
      userStore.setCurrentUser(data);
      companyStore.loadSettings();
      this.setState({ userLoaded: true });
    }).catch(({ response }) => {
      if (response.status === 401)
        this.setState({ userLoaded: true, serverUnauthorized: true });
      else if (response.status === 400)
        this.setState({ userLoaded: true, serverError: true });
      else
        this.setState({ userLoaded: true, serverError: true });
    });
    // section to catch application wide errors, happening later on the navigation
    Axios.interceptors.response.use(function (response) {
      // Do something with response data
      return response;
    }, function (err) {
      if (err.response.status >= 500) {
        this.setState({ userLoaded: true, serverError: true }); // <!-- THIS IS FAILING
        console.log('setstate run');
      }
      return Promise.reject(err);
    });
  }

render() {
    return (
         this.state.userLoaded ?
    <BrowserRouter>
      <ScrollToTop>
        <Switch>
          {
            this.state.serverUnauthorized ?
              <Route component={Page401} />
              :
              this.state.serverError ?
                <Route component={Page500} />
... simplified ...       
    );
  }
});

What I am doing wrong? Is there a better way to get this intercepted and error screen displayed?

Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • I think the problem is [binding of `this` in JS](https://javascript.info/bind). When you pass the error handler to the axios interceptor as `function`, `this` will not be bound to the current class' context. Try using a fat arrow function (`err =>`) when passing the handler to the response interceptor. – kidney Apr 12 '20 at 16:51
  • Define the axios interceptors as arrow functions. Check the duplicate ```Axios.interceptors.response.use((response) => { // Do something with response data return response; }, (err) => { if (err.response.status >= 500) { this.setState({ userLoaded: true, serverError: true }); // – Shubham Khatri Apr 12 '20 at 16:55

0 Answers0