Sohil Chamadia
Sohil Chamadia

Reputation: 426

Cancel previous call made using fetch API in Vue JS

I am working in laravel + VueJS application.In that there is a search functionality through which user can search any text then API will called to get data based on search text.So to call API in laravel "Fetch API" in VueJS is used.So now when any user press any keyword then everytime the method will be called to get the result.So due to that multiple request has been send.I just like to do that when any user type any text then everytime previous request must be cancelled.The code i have attached below which is used to call the API and fetch the data.

            searchProperties(search) {

            if (search != null && search != '') {
                this.review = false;
                this.clearSes = false;
                fetch('/search/' + search)
                    .then(res => res.json())
                    .then(res => {
                        if (res.status === 200) {
                            this.properties = res.data.properties;
                        }
                    });

            } else {
                this.clearSuggestions();
            }
        }

Thanks in advance!

Upvotes: 5

Views: 2691

Answers (1)

Veniamin Craciun
Veniamin Craciun

Reputation: 89

You could you an abortable fetch like this

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000);

fetch(url, { signal }).then(response => {
  return response.text();
}).then(text => {
  console.log(text);
});

See docs for more details.

Upvotes: 1

Related Questions