Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel previous call made using fetch API in Vue JS

Tags:

laravel

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!

like image 501
Sohil Chamadia Avatar asked Nov 07 '22 06:11

Sohil Chamadia


1 Answers

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.

like image 162
Veniamin Craciun Avatar answered Nov 25 '22 21:11

Veniamin Craciun