Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React abort/cancel AJAX request. Axios or XHR

I just develop a SPA and need help with the asynchronous requests I send by react componentDidMount to my server side (node). The queries work, but if I change quickly to the different pages, the setState functions within the ajax response are still running. Although the components are unmounted.

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

To avoid this error, I would like to abort/cancel the request which I send on componentWillUnmount if this is the correct way to do this.

I tried this with xml and with axios but it doesnt work. I hope you have a working example for me. Iam open for other request methods like fetch or something.

The code looks something like this (Axios), but it doesn't cancel the request:

import * as React from 'react';
import axios from 'axios';

let CancelToken = axios.CancelToken;
let source = CancelToken.source();

class MakeAjaxRequest extends React.Component {
  constructor() {
    super();
    this.state = {
      data: {}
    }
  }

  componentDidMount() {
    const that = this;

    axios.get('/user/12345', {
      cancelToken: source.token
    })
      .then(function (response) {
        if (axios.isCancel(response)) {
          console.log('Request canceled', response);
        } else {
          that.setState({
            data: response.data
          });
        }
      })
      .catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          // handle error
        }
      });
  }

  componentWillUnmount() {
    source.cancel('Operation canceled by the user.');
  }

  //....other stuff, like render the data
}
like image 796
Daniel Schink Avatar asked Oct 26 '17 08:10

Daniel Schink


1 Answers

Axios has the option of cancelling requests:

https://github.com/axios/axios#cancellation

Another way of preventing setState from firing on some kind of callback after the component is unmounted is to have a local boolean variable storing whether or not the component is mounted, i.e.

componentDidMount(){
   this._mounted = true;
}

componentWillUnmount() {
   this._mounted = false;
}

Then in the axios callback check whether _mounted is true before trying to call setState()

like image 114
Jayce444 Avatar answered Sep 18 '22 15:09

Jayce444