15

Router.push({pathname: '/card', query:{data: ObjectData}})

I get query as empty value could not pass object into it

Victor Anuebunwa
  • 2,553
  • 2
  • 24
  • 34
Poornima Shinde
  • 159
  • 1
  • 1
  • 3
  • 1
    What is `ObjectData` , can you post code that shows how it's created. Have you tried passing an example object into it, e.g: `{foo:bar}` - Empty value means its initialized but `ObjectData` is not accessible – Ramakay Jul 20 '20 at 13:07

4 Answers4

24

you can pass your params like this case:

router.push({
      pathname: '/card',
      query: { data: JSON.stringify(ObjectData)}
  })

and you can get params in card component like this:

JSON.parse(props.router.query.data);
Medisa
  • 379
  • 1
  • 3
  • 12
  • This should be accepted as the right answer. If you ever come across with the error `Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string'` just change the argument to `JSON.parse(props.router.query.data as string)` – akis Jun 25 '22 at 00:28
4

Ciao, in next.js you can pass query parameters like this:

Router.push({
  pathname: '/card',
  query: { name: 'Someone' }
})

And you retrieve it this way:

this.props.router.query.name

Supposing that your ObjectData is a JSON object, you could pass it like:

Router.push({pathname: '/card', query: ObjectData})
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
  • and what if i dont want to pass ObjectData in query and paas as a normal params as a object – Poornima Shinde Jul 20 '20 at 13:30
  • Ciao, I don't think you could do that. I'm reading next.js [docs](https://nextjs.org/docs/api-reference/next/router). As examples show, you ca pass props only using query props. – Giovanni Esposito Jul 20 '20 at 13:35
0

This doesn't work for me. It says Cannot read property query of undefined

I have an object of userData which I want to pass from nav component to userprofilePage.

So, in nav I write:

onClick={() => {
  Router.push({
    pathname: "/userProfilePage",
    query: { data: JSON.stringify(userData) },
  });
}}

and to retrieve in userProfilePage:

const router = useRouter();
const userData = JSON.parse(props.router.query.data);
Idrizi.A
  • 9,819
  • 11
  • 47
  • 88
Vaidehi S
  • 1
  • 1
0

this how you pass object as parameter in nextjs

  router.push({
  pathname: "/biodata",
  query: { data: "test" },
  });

and if it is a variable e.g id=12346

 router.push({
  pathname: "/biodata",
  query: { data: id },
  });

and you access that object in other component using these line of code

const router = useRouter();
const {
query: { data },
} = router;

i.e how to used it in new page .about page

import { useRouter } from "next/router"
export default function AboutPage() {
const router = useRouter()
const {
query: { data },
} = router
return <div>About us: {data}</div>
} 
RaySun
  • 139
  • 1
  • 5