简体   繁体   中英

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()
    }

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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM