haZya
haZya

Reputation: 334

How to get URL segments with next/navigation in Next.js

I’m currently working on a Next.js project and I’m trying to use the useSearchParams or useParams hook from the next/navigation to access URL segments. I have used Rewrite parameters to map source: '/chat/:id' to destination: '/chat' so it gets rewritten to the chat page with the :id segment. However, I’m encountering an issue where useParams is returning an empty object and useSearchParams returning null.

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

export default function MyComponent() {
  // Current URL -> '/chat/1' (/chat/:id)
  const params = useParams()
  const searchParams = useSearchParams()
  console.log("params", params) // This logs an empty object {}
  console.log("searchParams", searchParams.get("id")) // This logs null
}

I understand that useParams only returns the dynamic params like /chat/[id] but when I navigate to a URL like /chat/:id, I expect searchParams.get("id") to return the value for :id, but it’s returning null. With router.query from next/router it gives the correct value. Is there no way to access the :id segment using next/navigation?

Is this the expected behaviour for useSearchParams and useParams when trying to access URL segments, or am I missing something?

P.S. next/navigation doesn't seem to export beforePopstate or other router events either.

Edit: Just realized the usePathname() returns the pathname with the :id segment which is different from the behaviour of the pathname value returned from next/router which only returns /chat and that is the actual pathname.

Upvotes: 3

Views: 6720

Answers (1)

Arlle Brasil
Arlle Brasil

Reputation: 176

The useSearchParams hook function is used to get the values ​​that are placed after your page pathname, such filters and other values. For example, you can have http://appname/chat/[id] as your pathname, and you could searchhttp://appname/chat/1?value=2 at the browser.

Using useSearchParams().get("value") you'll get the value 2, and using useParams().id you'll get the value 1. You should use useParams to get the values ​​placed inside the pathname and use useSeachParams to get the values ​​that come after it.

Upvotes: 3

Related Questions