Next.js Discord

Discord Forum

Updates from window.history.pushState not reflected in Next.js routing

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
I'm trying to use query parameters to update filtering criteria in my app. [It looks like the proper way to do this in Next.js 14](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api) is to use the window.history.pushState method, the idea being that Next's navigation API will hook into changes called by this method and store the changes in internal state

However, I've found this not to be the case. When I manipulate history state using window.history.pushState, my changes aren't reflected by useSearchParams or usePathname.

Below, I've included the hook that I'm using to do this. Does anyone have some insight here? Is this a common bug or is something wrong with my implementation?

import { 
  usePathname,
  useSearchParams } from 'next/navigation'

const useQueryFilter = () => {
  const params = useSearchParams()
  const pathname = usePathname()

  const setQueryFilter = (key:string, value:string) => {
    const newParams = new URLSearchParams(params.toString())
    newParams.append(key, value)

    history.pushState(null, '', `${pathname}?${newParams.toString()}`)
  }

  const clearQueryFilter = () => {
    history.pushState(null, '', `${pathname}`)
  }


  return { setQueryFilter, clearQueryFilter }
}

export default useQueryFilter

0 Replies