angry kiwi
angry kiwi

Reputation: 11445

how to cancel the earlier fetch request and keep the last one during search

const controller = new AbortController()
const signal = controller.signal
const Search = ({ searchSuggestion }) => {
    const onkeychange = async (e) => {
        controller.abort()
        let string = e.target.value
        const suggest = await getSearchSuggestion({
            string,
            signal,
        })

    }
    return (
        <input
            type="text"
            autoComplete="off"
            placeholder="Search"
            onChange={onkeychange}
        />
    )
}

This canceling request code. The problem with this is, it cancel all the requests. While I only want to cancel requests of earlier keystrokes. And keep the last request alive.

Upvotes: 4

Views: 2642

Answers (2)

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12691

You are using the same controller/signal in all requests, you can save the previous controller like this :

const Search = ({ searchSuggestion }) => {
    const previousController = useRef();
    const onkeychange = async (e) => {
        if (previousController.current) {
          previousController.current.abort();
        }
        let string = e.target.value
        const controller = new AbortController()
        const signal = controller.signal
        previousController.current = controller;
        const suggest = await getSearchSuggestion({
            string,
            signal,
        })

    }
    return (
        <input
            type="text"
            autoComplete="off"
            placeholder="Search"
            className="search"
            onChange={onkeychange}
        />
    )
}

Upvotes: 4

Lazar Nikolic
Lazar Nikolic

Reputation: 4394

The problem is that you have one signal that is connected to all of your fetch requests. If you want to cancel only the last one, you should pass for every single fetch request new instance of AbortController and when you do the abort(), you should do that only on the AbortController instances that you want.

Upvotes: 0

Related Questions