Hey guys I am struggling a bit to get my head around an elegant way on how to fetch my globals in a Next application. I currently have a custom _app.tsx with getInitialProps where I do some async fetching to the Payload Rest API passing down the data to my global components e.g Header similar to the way it is implemented in the tutorial series
https://www.youtube.com/watch?v=bxWsZTtqs80. Now I was thinking about fetching the globals in each component in the useEffect hook instead of doing it in the custom app component to avoid passing down props and keep everything more isolated and I wanted to here about common solutions the community is handling globals fetching.
Using getInitialProps also leading to this warning: "Warning: You have opted-out of Automatic Static Optimization due to
getInitialProps
in
pages/_app
." Which concerns me although I am using SSR anyway.
currently in _app.tsx
MyApp.getInitialProps = async (appContext) => {
[...]
const getGlobals = (slug: string) => {
return fetch(
`${process.env.NEXT_PUBLIC_SERVER_URL}/api/globals/${slug}?locale=${locale}`
).then((res) => res.json());
};
const [header, footer, social, settings] = await Promise.all([
getGlobals("header"),
]);
return { ...appProps, header };
};
Hey @Chris_Heinz - have you tried using
payload.findGlobal()
?
You can see an example of how to use it in the next-payload repo here:
https://github.com/payloadcms/next-payload-demo/blob/main/app/(site)/layout.tsxYes using the local API leads to an error as I am using this template
https://github.com/payloadcms/nextjs-custom-serveras a base unfortunately the local API is not available. Actually I think there is no big difference whether I am querying the globals on app level and pass it down or if I am directly querying in the component itself. I just thought there might be a best practice to it. Anyway thanks for replying 🙂 @jesschow
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.