fetch data once on the server for multiple pages
Unanswered
Ocicat posted this in #help-forum
OcicatOP
I'm working on an app structured like this:
- /projects
- /projects/archive
- /team
- /team/archive
Today I'm fetching data from Supabase on each pages. I have 3 Supabase calls for each pages. Every time I'm switching navigation to another page, it seems that the data is fetched again and the loading time is pretty slow.
Since I want to use Supabase realtime after the first render to get data updates, my goal is to load the data first for all path, and then use realtime. I want to first fetch the data on the server and then everything else be on the client.
How can I fetch data once for several pages? I was under the impression that layouts was not the place to do that. Middleware?
- /projects
- /projects/archive
- /team
- /team/archive
Today I'm fetching data from Supabase on each pages. I have 3 Supabase calls for each pages. Every time I'm switching navigation to another page, it seems that the data is fetched again and the loading time is pretty slow.
Since I want to use Supabase realtime after the first render to get data updates, my goal is to load the data first for all path, and then use realtime. I want to first fetch the data on the server and then everything else be on the client.
How can I fetch data once for several pages? I was under the impression that layouts was not the place to do that. Middleware?
15 Replies
use react-query to prefetch the query server side
OcicatOP
Thanks @Ray. This looks really interesting. I'm just wondering if there was a way to achieve a similar scenario without having to use an external library.
OcicatOP
That look very interesting though. I should try it out.
Layout are the right palce to do that, what's blocking you specifically?
In a serverless paradigm, you can't really do that (that's why it took centuries for Next to bring layouts, it's not "idiomatic" of serverless)
because 1 page might be 1 app (or not but that depends on your host, you are not supposed to control page bundling)
what you can do instead, is relying on caches
if your pages happen to be bundled together and run on the same machine, they will benefit from the same cache
if not, they will refetch the data
a common pattern would be using eg node-cache, and cache the data fetching call (not the result, the actual promise to the call, be careful with this common trap)
but layouts might be easier to use here
OcicatOP
But you are not supposed to fetch data on layouts, right?
By the way I'm trying react-query and this thing is just MAGIC ✨
I love their devtools. Fetching and mutate data is just soooo much simpler.