5

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!

2
  • 3
    You should really be debouncing this function too! See lodash's debounce method. Commented Jul 20, 2020 at 10:15
  • 1
    Totally agreed with @KurtFriars This video explains it well. Commented Jul 21, 2020 at 7:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey,I have tried code given by you but using that it also cancel current request as well.
@SohilChamadia Have you try to use different signal for different requests?
For every request the signal will be different?
Yes, since we are passing the signal as parameter to fetch function then it must be recreated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.