You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
After spending quite some time documenting myself on the perks of stores in sveltekit, their risk when used with SSR, i think i understood that the only way to be 100% sure i don't fuck up is creating stores with a context in the layout.svelte.
So here i report the current implementation i put up, getting some inputs around, and ask for your opinions on it:
create scoped stores with typesafe typings
I first created an util file:
// lib/utils/context.tsimport{getContext,setContext}from'svelte';/** * The context object. */interfaceContext<T>{get: ()=>T;set: (context: T)=>T;}functionrandomContextName(){return`$$context_${crypto.randomUUID()}`;}/** * Creates a context. */exportfunctioncreateContext<T>(key: symbol|string=randomContextName()): Context<T>{return{get: ()=>getContext<T>(key),set: (context: T)=>setContext(key,context),};}
with this function, i can create a store under lib/stores/ContextStore.ts
import{typeStatic,Type}from'@sinclair/typebox';importtype{Writable}from'svelte/store';import{createContext}from'../utils/context';exportconstContextStoreSchema=Type.Object({name: Type.String(),age: Type.Number(),});exporttypeTContextStore=Static<typeofContextStoreSchema>;// this doesn't set a context, it only prepares its typesexportconstContextStore=createContext<Writable<TContextStore>>(Symbol('context'));
can now use this prepared set and get context functions to create the store in +layout.svelte and use the get wherever i need to access the store.
This way, it's like having a single exported store from the lib directory.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
After spending quite some time documenting myself on the perks of stores in sveltekit, their risk when used with SSR, i think i understood that the only way to be 100% sure i don't fuck up is creating stores with a context in the layout.svelte.
So here i report the current implementation i put up, getting some inputs around, and ask for your opinions on it:
create scoped stores with typesafe typings
I first created an util file:
with this function, i can create a store under
lib/stores/ContextStore.ts
can now use this prepared set and get context functions to create the store in
+layout.svelte
and use the get wherever i need to access the store.This way, it's like having a single exported store from the lib directory.
Is there a better way to to it?
Is this actually safe?
Beta Was this translation helpful? Give feedback.
All reactions