I am following the Next.js tutorial. Currently I am stuck on this page:
https://nextjs.org/learn/dashboard-app/adding-search-and-pagination
After a thorough web search with no clear answer, I would like to consult you. Thanks.
function handleSearch(term: string) {
const handleSearch = useDebouncedCallback((term) => {
console.log(`Searching... ${term}`);
const params = new URLSearchParams(searchParams);
if (term) {
params.set('query', term);
} else {
params.delete('query');
}
replace(`${pathname}?${params.toString()}`);
}, 300);
}
The idea is that whatever is filled into the input field, is passed on as a parameter to the url and in turn used to search in the database. Without the useDebouncedCallback function the database will be queried after each typed letter. The useDebouncedCallback should delay the database query until 300ms after the user stops typing.
The tutorial explains that in the console log, before the useDebouncedCallback function is added, the the output for a search for the name ‘Emil’ would be this:
Searching... E
Searching... Em
Searching... Emi
Searching... Emil
And after adding the useDebouncedCallback function, the output for typing ‘Emil’ would only display the whole search term, like so:
Searching... Emil
However, my console still displays the letter-by-letter output. The url search parameter also updates after each letter and not 300ms after the final letter. Thus still querying the database after each letter.
My question is: Is there an error in this code (which is directly copied from the tutorial) or is this expected behavior? Am I misunderstanding something?
2
Answers
It turned out to be an issue with my local environment. What the exact issue was, is still unclear. But I have cloned my git repository on a different computer and it worked just fine on there. After deleting my local file folder and re-cloning it from github, it now works.
Conclusion is: there was nothing wrong with the code.
This is from the documentation you provided. This code only prevents the rapid re running of the function inside, if you type slower than 300ms per character you will see each letter.