A
A
Alexey Sklyarov2021-05-17 12:32:28
Vue.js
Alexey Sklyarov, 2021-05-17 12:32:28

How to fix problems with search results when input changes?

There is a component. which searches for materials when you enter a search word in input

Searchbox.vue

<template>
    <div>
        <input type="text" name="query" :placeholder="placeholder" v-model="query" v-on:keyup="fetch">
        <div class="search-box__result" v-show="query" ref="result_list" id="search-results">
            <ul v-if="results.length > 0">
                <li v-for="result in results.slice(0,10)" :key="result.id">
                    <!--  -->
                </li>
            </ul>
            <div class="search-box__message" v-else>По данному запросу ничего не найдено</div>
            <div class="search-box__loading"></div>
        </div>
    </div>
</template>

<script>

export default {
    data() {
        return {
            query: null,
            results: [],
        }
    },
    props: ['placeholder'],
    methods: {
        fetch() {
            axios.get('api/search/posts', { params: { query: this.query } })
                .then(response => {
                    this.results = response.data
                    this.nprogress.done();
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }
}
</script>



The search works fine, but I constantly encounter a bug in its work: if I quickly enter some search phrase, for example PostName, in the search results, only this post will appear to me at first, and then the search results from the very first request are immediately shown (when the first letter was entered search word). If I slowly enter a word letter by letter, everything works properly, as soon as I enter it quickly, then the correct output is replaced by one of the previous ones.

What could be the reason for this behaviour?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-05-17
@0example

We need to cancel the previous request when starting a new one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question