dynamic metadata data fetch call
Answered
rex1410 posted this in #help-forum
rex1410OP
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?
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
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...
}
5 Replies
Hi,
You can use the React
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
rex1410OP
@Julienng thanks for sharing this I will try this out
rex1410OP
@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)
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)
It is available in the app router. No need to install anything canary.
The app router automatically uses React canary, it works, no need to worry about it.
The app router automatically uses React canary, it works, no need to worry about it.
rex1410OP
ahh alright, thats perfect. Thanks a lot for the clarification