Search code examples
reactjsaxioscancellationtokensourcecancellation-tokenrequest-cancelling

Axios cancel token cancelling every request


I' trying to implement cancelToken API so that whenever i'm making a request to server to fetch results on every key stroke, only the last request should get processed, however i have implemented the axios cancel token API and it seems to cancel every request, what am i doing wrong here? This function is getting called on every key stroke.

getProductLists2 = async () => {


        let formData = new FormData()

        const { start, limit } = this.state

        formData.append('start', start)
        formData.append('limit', limit)

        formData.append('product_title', this.state.searchTitle)
        formData.append('product_sku', this.state.searchSKU)

        let cancel;

        Axios({
            method: 'POST',
            url: BASE_URL + '/listProduct',
            // headers: { 'Content-Type': 'multipart/form-data' },
            data: formData,
            cancelToken: new Axios.CancelToken(c => cancel = c)
        })
            .then(products => {
                if (products && products.data.productList && products.data.productList.length > 0) {
                    this.setState({ productList: products.data.productList, totalProducts: products.data.productTotal })
                }
            })
            .catch(err => toast.error('Something went wrong'))
        console.log(cancel, 'h')
        cancel && cancel()
    }

Solution

  • You should cancel the previous cancelToken before making a new axios call. When you make you first request, save the cancelToken. Then when you make the second request, check if there already is a cancelToken and cancel it, then make your second axios call.

    It also might be a good idea to debounce your getProductLists2 to limit the rate of calls

    This is how I do it:

        // Cancel the previous axios token if any
        if (this.cancel) this.cancel.cancel();
        // Get a new token
        this.cancel = axios.CancelToken.source();
        axios
            .get(myURL, { cancelToken: this.cancel.token })
            .then((res) => {
              console.log(res.data);
            })
            .catch((error) => { console.log(error); });