How do you share state between load functions #10715
Replies: 4 comments 19 replies
-
There isn't a clean way to achieve this at the moment. I tried to convince the team multiple times that we absolutely need this functionality. |
Beta Was this translation helpful? Give feedback.
-
You can use the // hooks.server.js
export const handle = async ({ event, resolve }) => {
event.client = buildGraphQlClient();
return await resolve(event);
} // /any_other_page/+page.server.js
export const load = async ({ locals }) => {
const data = await locals.client.get('stuff_stuff');
} |
Beta Was this translation helpful? Give feedback.
-
Starting a new thread because the other one went a bit astray. Let's say we make a file // lib/graphql/client.js
let client;
export default function getClient(fetch) {
if (client) return client;
client = buildClient(fetch);
return client;
} Now using this function in a Obviously there is no way to share the graphQlClient between client/server, those will be two different instances. |
Beta Was this translation helpful? Give feedback.
-
I worked out a solution for universal load functions: https://gist.github.com/david-plugge/33cd821a4c829059f67ce18468b8dfca. |
Beta Was this translation helpful? Give feedback.
-
Hi, I'm using a graphql client in svelte kit particularly I'm using Apollo-client but I believe the issue applies to all other clients swell.
The concept of the graphql-client is that all graphql requests goes through it and I can do a lot of caching and state management.
The general idea is as follows
And now all subsequent components can access the graphql client on the context and use it to query data.
The problem is that if I wish to use it in a subsequent load function I have to await parent data potentially causing waterfalls
Does anyone have a good idea on how to avoid this? while preserving the fact that I can use a single client for all graphql requests?
Beta Was this translation helpful? Give feedback.
All reactions