I want to programmatically pass data between pages when navigating with useRouter
's push()
method. The following code redirects me to the url http://localhost:3000/[object%20Object]
, but I was expecting it to take me to http://localhost:3000/home?userid=deepeshdm&orderid=12345
. Why does it do this, and how do I fix it?
// app/page.js
"use client"
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter();
const handleClick = () => {
router.push({
pathname: '/home',
query: { userid: 'deepeshdm', orderid: '12345' },
});
};
return (
<>
<h1 align="center"> Root Page </h1> <br/>
<button onClick={handleClick}> GO HOME </button> <br/>
</>
)
}
I want to programmatically pass data between pages when navigating with useRouter
's push()
method. The following code redirects me to the url http://localhost:3000/[object%20Object]
, but I was expecting it to take me to http://localhost:3000/home?userid=deepeshdm&orderid=12345
. Why does it do this, and how do I fix it?
// app/page.js
"use client"
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter();
const handleClick = () => {
router.push({
pathname: '/home',
query: { userid: 'deepeshdm', orderid: '12345' },
});
};
return (
<>
<h1 align="center"> Root Page </h1> <br/>
<button onClick={handleClick}> GO HOME </button> <br/>
</>
)
}
Share
Improve this question
edited Feb 7, 2023 at 15:03
Will
1,2041 gold badge13 silver badges35 bronze badges
asked Feb 7, 2023 at 13:57
deepeshdmdeepeshdm
631 silver badge4 bronze badges
1 Answer
Reset to default 8It appears for Next.js 13, router.push()
only accepts a string.
It looks like they dropped pathname
and query
for read-only hooks.
The way around this is to use template literal string interpolation: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals
router.push(`/home?userid=${userid}&orderid=${orderid}`);
I hope this helps.