Created
March 15, 2023 12:59
-
-
Save tlux/0d87ec94581866567dad2ce64fa7c527 to your computer and use it in GitHub Desktop.
Simple TypeScript wrapper to set and get Svelte contexts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getContext, setContext } from "svelte"; | |
/** | |
* The context object. | |
*/ | |
export interface Context<T> { | |
get: () => T; | |
set: (ctx: T) => T; | |
} | |
function randomContextName() { | |
return `$$context_${crypto.randomUUID()}`; | |
} | |
/** | |
* Creates a context. | |
*/ | |
export function createContext<T>(key: any = randomContextName()): Context<T> { | |
return { | |
get: () => getContext<T>(key), | |
set: (ctx: T) => setContext(key, ctx), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is one way to use it. Note that you should use context selectively when prop passing becomes a burden or isn't practical.
Put the above snippet at
src/lib/context.ts