fr0standsn0w
fr0standsn0w

Reputation: 23

Next Js 13 routing

how I can add dynamicly and remove query parameter with Next Js useRouter from "next/navigation" with App Routing? I need add filter to query, such as add filters=219,213 with .../hotels?id=123&type=hotel

I tried router replace to add new query params

Upvotes: 0

Views: 1112

Answers (1)

Gasanov
Gasanov

Reputation: 3399

You will need to use useSearchParams and usePathname to get query and pathname. You can also use router.replace if you want to update existing history record instead of adding new one.

'use client'

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

export default function Page() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()

  const updateQuery = () => {
    const newUrlParams = new URLSearchParams(searchParams.toString())
    newUrlParams.set('filters', ['219', '213'].join(','))
    router.push(`${pathname}?${newUrlParams}`)
  }

  return (
    <div>
      <button onClick={updateQuery}>Update filter</button>
    </div>
  )
}

Upvotes: 5

Related Questions