Next.js Discord

Discord Forum

Search params not updating using router.push or router.replace

Unanswered
roopaish posted this in #help-forum
Open in Discord
so here when i click a button i am removing the city search params by calling setUrlparams({city:undefined})

As you can see in the network tab, the url that gets requested does not have city on it meaning it might be pushing correctly but the url itself is not updating.

const setUrlParams = (params: Partial<T>) => {
    const urlSearchParams = new URLSearchParams(searchParams.toString())

    Object.entries(params).forEach(([key, value]) => {
      if (!value) {
        urlSearchParams.delete(key)
      } else if (Array.isArray(value)) {
        if (value.length) {
          urlSearchParams.set(key, value.join(","))
        } else {
          urlSearchParams.delete(key)
        }
      } else {
        urlSearchParams.set(key, value)
      }
    })

    const newQuery = urlSearchParams.toString()
    router.replace(`${pathname}${newQuery ? `?${newQuery}` : ""}`, options)
  }

10 Replies

bump
not really sure what the options contains, but I assume you checked it does not set something that could cause this?
You probably dont want this functionality, but to test with try to use .push. .replace overrides top item at the stack, .push adds on, it might work and prove that the URL does indeed get correctly updated and that it has to do with .replace specifically
i tried push too it didnt work, if i use Link tag it works, router.push and router.replace do not work. i might just fallback to using Link tag but hidden then click it programmatically
options only has scroll:boolean, which is set to false
I assume pathname is valid and correct? You really need to share more context for this.
i am fetching the data in the server and passing it to client components, and in one of the client components i am using router.push or replace, to change the search params
thing is it works sometimes and sometimes not