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), | |
}; | |
} |
Hi @tlux, thanks for the helper. Could you also show an example usage - how to create and re-use context across components with this helper?
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
// src/ctx.ts
// Create a shared context to use in any component
import { createContext } from '$lib/context'
import type { Writable } from 'svelte/store'
export const ctx = createContext<Writable<string>>()
<!-- src/App.svelte -->
<script lang="ts">
import { ctx } from './ctx'
import Bar from './Bar.svelte'
// Set the context value (a writable store)
let store = writable<string>('Hello, World!')
ctx.set(store)
</script>
<Bar />
<!-- src/Bar.svelte -->
<script lang="ts">
import { ctx } from './ctx'
// Read the context value (a writable store)
let msg = ctx.get()
function bye() {
$msg = 'Goodbye, World!'
}
</script>
Message: {$msg}
<button on:click={bye}>bye</button>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this came in handy!