Home > Back-end >  pass object from one page to another page NextJS
pass object from one page to another page NextJS

Time:01-25

I want to pass nested object data from one page to the next page. I want to pass the object. We can not use localStorage or sessionStorage because we have to consume object values from getServerSideProps. We do not use here router query as it passes a query that takes key pair value.

CodePudding user response:

You can use the Link component from next/link, something like:

  <Link 
      href={{ 
          pathname: 'path-to-your-page', 
          query: 'data you want to pass' 
          }} 
  >
      You other page
  </ Link>

From your other page, you can then benefit form the useRouter nextjs hook:

const router = useRouter();
const dataFromPreviousPage = router.query;

CodePudding user response:

getServerSideProps and getStaticProps run on the server so they do not have any relation with your components and your hooks, so there is no way that they have access to any provider or any hook.

but since getServerSideProps runs on every request you can use the request to pass data to it. one solution is to pass data in the url.

We do not use here router query as it passes a query that takes key pair value

you can pass an object with router query you just have to stringify it before passing it then parse data when you recieve it

let suppose that you have page A with getServerSideProps you can call it like this :

const router = useRouter();
router.push({
pathname: '/url_of_page_A',
query: { 
data: JSON.stringify( { a: 'value', b: 'another value'} ) ;
},
});

Now in your page A inside getServerSideProps you can access data via context query :

export async function getServerSideProps(context) {
const data = JSON.parse(context.query.data);
}

CodePudding user response:

In Next.js, you can pass data from one page to another using the router.push or router.replace methods. You can pass the object as a state object in the second argument. For example:

    router.push({
  pathname: '/next-page',
  state: { data: yourObject }
})

On the next page, you can access the data using useRouter hook, like this:

import { useRouter } from 'next/router'
  const NextPage = () => {
  const router = useRouter()
  const { data } = router.query

  return (
    <div>
       {JSON.stringify(data)}
    </div>
  )
}

It is important to note that you can only pass strings and numbers in the query, so if the object contains non-string data, you should stringify it before passing it to the state, and parse it on the next page.

  • Related