Shamoon
Shamoon

Reputation: 43569

How can I reload a URL with a new query parameter with NextJS?

I have:

<Link as={`/app/create?keyword=happy`} href="/app/create" passHref>
  My words!
</Link>;

The URL I'm currently on is http://localhost:3000/app/create?keyword=sad

When I click the link, the URL does update, but where I have:

useEffect(() => {
  console.log(router.query);
}, [router]);

it just shows {}.

How can I be updated when the router.query updates?

Upvotes: 1

Views: 2773

Answers (2)

tmhao2005
tmhao2005

Reputation: 17514

In nextjs, as you use prop as in <Link />, it's supposed to be used with a dynamic route to fill the parameter.

For example, you have a page user/[id].js, then you use as to pass the argument:

<Link as="/user/1" href="user/[id]" />

In your case, I don't think you should use as property, you simply remove that prop and pass keyword directly in href, then it should work:

<Link href="/app/create?keyword=happy" passHref>
  My words!
</Link>

Upvotes: 1

felixmosh
felixmosh

Reputation: 35553

useEffect gets as a second parameter a list of dependencies.

When you pass it the router object (which is a singleton) it won't recognize the change, because it doesn't make a deep check but a reference only.

Therefor, you should pass the query value it self.

useEffect(() => {
  console.log(router.query);
}, [router.query.keyword]);

Upvotes: 0

Related Questions