Next.js Discord

Discord Forum

Passing data with a redirect

Answered
Jumbo flying squid posted this in #help-forum
Open in Discord
Jumbo flying squidOP
Say you have a list of objects and when you select one, you get a detail page with that objects data. Is there a way to pass the already fetched object data from one page to the other? I'd like to not call another fetch in the detail page since its already fetched in the list page.
I don't want to pass it as a query param since that is a bit jank

Thank you!
Answered by Ray
no, we can't pass data from page to page as the doc suggest us to [fetch data where its needed](https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed)
since the fetch result is cached by default, you could try something like this
const getObjects = async () => fetch('url', { cache: 'force-cache' }).then(res => res.json())

// objects/page.tsx
async function PageList() {
  const objects = await getObjects()

  // render page
}

// objects/[id]/page.tsx
async function Page({params}) {
  const object = (await getObjects()).find(o => o.id === params.id)
  if (!object) notFound()

  // render page
}
View full answer

2 Replies

@Jumbo flying squid Say you have a list of objects and when you select one, you get a detail page with that objects data. Is there a way to pass the already fetched object data from one page to the other? I'd like to not call another fetch in the detail page since its already fetched in the list page. I don't want to pass it as a query param since that is a bit jank Thank you!
no, we can't pass data from page to page as the doc suggest us to [fetch data where its needed](https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#fetching-data-where-its-needed)
since the fetch result is cached by default, you could try something like this
const getObjects = async () => fetch('url', { cache: 'force-cache' }).then(res => res.json())

// objects/page.tsx
async function PageList() {
  const objects = await getObjects()

  // render page
}

// objects/[id]/page.tsx
async function Page({params}) {
  const object = (await getObjects()).find(o => o.id === params.id)
  if (!object) notFound()

  // render page
}
Answer
Jumbo flying squidOP
ahh nice ok thanks!