简体   繁体   中英

How to pass additional data to getserversideprops from another page in Nextjs?

I want to pass projectID from the previous page (/projects ) to the ( /project/[projectName] ). Therefore, in order to fetch a project details, i have to fire an API endpoint with projectID.

What is the right way to pass projectID from the previous page and also how to access it in the getServersideProps method.

In the /project/[projectName] page,

export async function getServerSideProps(){
// Here i want to access the projectID sent from the previous page
const data = await fetchData();
return {
    props: data,
  };
}

Query/param prop will have access to the projectName but not projectID.

As serverSideProps will run each time the page is loaded, you can't pass data from one page to another.

What you can do, is either pass data using useContext or if it's general data that you are going to use on all your pages you can fetch it directly on to the _app.js and pass it for all the children components.

This is an example using useContext.

This are the docs fetching on the _app.js. (check the commented code)

You can even combine both techniques and set the data on the _app.js and the consume it on any page or component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM