My search application provides real-time suggestions as users type in the search box. I utilize 'fetch' to retrieve these suggestions from an API with each character input by the user. However, there is a challenge when users quickly complete their search query before the suggestions are fetched - I need to cancel the fetch request in such cases.
In a previous React version of my application, I successfully utilized AbortController to cancel requests, but this functionality seems to be non-functional in Next.js.
Upon investigation, it appears that Next.js lacks access to AbortController during page generation, similar to the issue I encountered with 'window.innerWidth.'
To address this limitation, I implemented a solution using 'useEffect,' which worked effectively with 'window.'
const [size, setSize] = useState(0)
useEffect(() => {
setSize(window.innerWidth)
}, [])
However, applying a similar approach to AbortController did not yield the expected results:
let suggestionsController;
useEffect(() => {
suggestionsController = new AbortController();
},[])
Despite initializing 'suggestionsController' within the useEffect hook, it remained undefined when attempting to use it.
Subsequently, I experimented with leveraging 'useRef' for the same purpose:
const suggestionsControllerRef = useRef(null)
useEffect(() => {
suggestionsControllerRef.current = new AbortController();
},[])
This section highlights the process of fetching and aborting suggestions:
async function fetchSuggestions (input){
try {
const response = await fetch(`url/${input}`, {signal: suggestionsControllerRef.current.signal})
const result = await response.json()
setSuggestionsList(result)
} catch (e) {
console.log(e)
}
}
Abort logic incorporated into search event handling:
function handleSearch(word) {
suggestionsControllerRef.current.abort()
router.push(`/dictionary/${word}`)
setShowSuggestions(false)
}
While the initial implementation works flawlessly, subsequent searches trigger errors in the 'fetchSuggestions' function, resulting in "DOMException: Failed to execute 'fetch' on 'Window': The user aborted a request" being logged to the console.
If anyone has insights on how to properly implement AbortController in Next.js, I welcome your guidance.