NextJS Search Query URL with Debounce

2k Views Asked by At

I want to implement a instant Search Field with a Debounce. So when I stop typing (after 500ms), starts the Search, and the search query is now also in de url-param. My Problem is, I need to sync the url-query and the Input Field, so when I stop typing, the search query goes in the url-query. But for e.g. when I switch the page and go back (so the search is now in the url-query, but the input field is empty) i need, that the url-query goes in the input field.

The API request is with a GraphQL Search Variable.

edit: This is a Git-Gist for the existigin Code

2

There are 2 best solutions below

1
On

You can use Shallow Rounting

When you update the input field you also update the URL

router.push('/?search=yourQuery', undefined, { shallow: true })

Setting "shallow" to true, will update the URL without reloading the page.

You can see more information about Shallow here: https://nextjs.org/docs/routing/shallow-routing

And to fix your problem when you go back, you can try with useeffect with no dependencies to update your input if the URL has some query.

0
On

What fixed it for me was to await the router.push in the onChange event handler