Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel axios get request when typing reactjs

Tags:

reactjs

axios

I'm creating an autocomplete function, so basically whenever I type on search box it will cancel the previous http get request. I checked the jQuery ui autocomplete and that's what they did. Is that possible in axios if yes how can I implement it. So far here's my code for http get request:

export function autocompleteSearchTest(value){
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`,{
        params: {
            q: value
        }
    })
    .then(response => {
        return response.data.response;
    })
    .catch(error => {
        const result = error.response;
        return Promise.reject(result);
    });
}

Here's the screenshot when I type on the search box:

enter image description here

as you can see it doesn't cancel the previous http get request.

like image 549
Sydney Loteria Avatar asked Mar 20 '17 06:03

Sydney Loteria


People also ask

How do I cancel axios?

Log in to your account profile to manage your Axios Pro subscription. After logging in, click the Axios Pro section in the left hand menu. You'll be able to view your current subscription information, update preferences, and cancel if desired.

How does axios cancel work?

cancel() method, this will cause Axios to trigger an Error, even is the request is seemingly resolve, causing the promise to pass through to the Catch statement. At that point in time, if I don't do anything to check for the error, then React Async will render the IfRejected path, which is undesirable.

How does axios allow cancellation request and request timeout?

How Does Cancellation Actually Work? Under the hood, when you cancel() a request, Axios calls ClientRequest#abort() in Node. js or XMLHttpRequest#abort() in the browser. However, this does not guarantee that the HTTP request doesn't end up getting sent to the server.


1 Answers

Since axios v0.15 you can cancel request:

You can also create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

For more information please have a look Cancellation. And according to your code:

import React from 'react'
import axios from 'axios';

export function autocompleteSearchTest(value) {
    if (cancel != undefined) {
        cancel();
    }
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`, {
        cancelToken: new CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            cancel = c;
        }),
        params: {
            q: value
        }
    })
        .then(response => {
            return response.data.response;
        })
        .catch(error => {
            const result = error.response;
            return Promise.reject(result);
        });
}

var CancelToken = axios.CancelToken;
var cancel;

export class AutoComplete extends React.Component {

    constructor() {
        super()
        this.state = {
            search: ''
        };
        this.handleSearchChange = this.handleSearchChange.bind(this);
    }

    handleSearchChange(event) {
        const target = event.target;
        const value = target.value;
        this.setState({
            search: value
        });
        autocompleteSearchTest(value)
    }

    render() {
        return (
            <div className="App-intro Dialog-section">
                <h2>AutoComplete</h2>
                <div className="form-control">
                    <label htmlFor="password">Lookup :</label>
                    <input name="search" type="text" value={this.state.search}
                           onChange={this.handleSearchChange}
                           id="password" ref="password" placeholder="Enter line"/>
                </div>
            </div>
        )
    }
}

export default AutoComplete;

And here it's enter image description here

like image 94
Vladislav Kysliy Avatar answered Nov 15 '22 21:11

Vladislav Kysliy