Skip to content

Instantly share code, notes, and snippets.

@tlux
Created March 15, 2023 12:59
Show Gist options
  • Save tlux/0d87ec94581866567dad2ce64fa7c527 to your computer and use it in GitHub Desktop.
Save tlux/0d87ec94581866567dad2ce64fa7c527 to your computer and use it in GitHub Desktop.
Simple TypeScript wrapper to set and get Svelte contexts
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),
};
}
@danawoodman
Copy link

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