Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 6 additions & 15 deletions apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,27 +84,18 @@ Svelte will warn you if you get it wrong.

## Type-safe context

A useful pattern is to wrap the calls to `setContext` and `getContext` inside helper functions that let you preserve type safety:
As an alternative to using `setContext` and `getContext` directly, you can use them via `createContext`. This gives you type safety and makes it unnecessary to use a key:

```js
/// file: context.js
```ts
/// file: context.ts
// @filename: ambient.d.ts
interface User {}

// @filename: index.js
// @filename: index.ts
// ---cut---
import { getContext, setContext } from 'svelte';

const key = {};

/** @param {User} user */
export function setUserContext(user) {
setContext(key, user);
}
import { createContext } from 'svelte';

export function getUserContext() {
return /** @type {User} */ (getContext(key));
}
export const [getUserContext, setUserContext] = createContext<User>();
```

## Replacing global state
Expand Down
12 changes: 12 additions & 0 deletions apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,16 @@ function beforeUpdate(fn: () => void): void;

## createContext

<blockquote class="since note">

Available since 5.40.0

</blockquote>

Returns a `[get, set]` pair of functions for working with context in a type-safe way.

`get` will throw an error if no parent component called `set`.

<div class="ts-block">

```dts
Expand Down Expand Up @@ -365,6 +373,8 @@ function getAllContexts<
Retrieves the context that belongs to the closest parent component with the specified `key`.
Must be called during component initialisation.

[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.

<div class="ts-block">

```dts
Expand Down Expand Up @@ -502,6 +512,8 @@ and returns that object. The context is then available to children of the compon

Like lifecycle functions, this must be called during component initialisation.

[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.

<div class="ts-block">

```dts
Expand Down