Next.js Discord

Discord Forum

Save API Call Response, so that I can use it from anywhere.

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
Hi, in my Next.js app I fetch restaurant data via the route /restaurant/[id]. Where should I store the restaurant data, so that I can access it from different components, for example Cart.tsx, or any other? Much appreciating any help.

9 Replies

Avatar
French Lop
You could store it inside a context, using the useContext hook
Avatar
Asian black bearOP
but then I can't use it with SSR, right?
I was thinking of the same (in a zustand store)
Avatar
French Lop
Ah, then you can fetch it in the getInitalProps, then set it as a data value passed into your page, where you can then set it into some context, no?
Admittedly I use NextJS with an Express backend, but pretty sure the same applies
Avatar
Rafael Almeida
If you are using the app dir, fetch requests will automatically be deduped by Next, so you can keep repeating the same request in multiple components and they will all use the same request. This removes the need to use context to pass the request results down to other components
Avatar
Asian black bearOP
My Cart.tsx Component is using "use client", can I still fetch it through SSR in this component, or do I need to create a wrapper component with SSR with this?
Avatar
Rafael Almeida
It would be better to wrap it with a server component, so it can fetch the data and pass it to the client component
Avatar
Asian black bearOP
Thanks much. I also want to create helper functions, such as "getDishById()". So it looks like with your suggested implementation I would always have to pass in the restaurantData, which we previously fetched, as a parameter as well?