Next.js Discord

Discord Forum

dynamic metadata data fetch call

Answered
rex1410 posted this in #help-forum
Open in Discord
So I have to get the dynamic metadata for a website from the DB, but what I realise is that the initial data load for that website is also happening on server side.

Is there any way to reduce the repeated call? can I reuse the data from either layout or generateMetadata? Or do I HAVE to make 2 calls?
Answered by Julienng
Hi,

You can use the React cache API ([doc](https://react.dev/reference/react/cache#cache))

cache from React will cache data per request.

const getMyData = cache(async function() {/* get data from DB */});

export async function generateMetadata() {
  const myData = await getMyData();

  // rest of metadata ...
}

export default function MyPage() {
  const myData = await getMyData();
  // rest of code...
}
View full answer

5 Replies

Hi,

You can use the React cache API ([doc](https://react.dev/reference/react/cache#cache))

cache from React will cache data per request.

const getMyData = cache(async function() {/* get data from DB */});

export async function generateMetadata() {
  const myData = await getMyData();

  // rest of metadata ...
}

export default function MyPage() {
  const myData = await getMyData();
  // rest of code...
}
Answer
@Julienng thanks for sharing this I will try this out
@Julienng hello.
The cache API you shared is only in the canary build, is there any other solution that I can use instead of going on the canary build (I am not very knowledegable about the builds other than the stable build so please advice)