Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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.

like image 752
angry kiwi Avatar asked Oct 26 '25 09:10

angry kiwi


1 Answers

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}
        />
    )
}
like image 126
Mohamed Ramrami Avatar answered Oct 29 '25 00:10

Mohamed Ramrami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!