Skip to content

Commit 7b42583

Browse files
Sync svelte docs (#1617)
sync svelte docs Co-authored-by: svelte-docs-bot[bot] <196124396+svelte-docs-bot[bot]@users.noreply.github.com>
1 parent 913c2cb commit 7b42583

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -84,27 +84,18 @@ Svelte will warn you if you get it wrong.
8484

8585
## Type-safe context
8686

87-
A useful pattern is to wrap the calls to `setContext` and `getContext` inside helper functions that let you preserve type safety:
87+
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:
8888

89-
```js
90-
/// file: context.js
89+
```ts
90+
/// file: context.ts
9191
// @filename: ambient.d.ts
9292
interface User {}
9393

94-
// @filename: index.js
94+
// @filename: index.ts
9595
// ---cut---
96-
import { getContext, setContext } from 'svelte';
97-
98-
const key = {};
99-
100-
/** @param {User} user */
101-
export function setUserContext(user) {
102-
setContext(key, user);
103-
}
96+
import { createContext } from 'svelte';
10497

105-
export function getUserContext() {
106-
return /** @type {User} */ (getContext(key));
107-
}
98+
export const [getUserContext, setUserContext] = createContext<User>();
10899
```
109100

110101
## Replacing global state

apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,16 @@ function beforeUpdate(fn: () => void): void;
224224

225225
## createContext
226226

227+
<blockquote class="since note">
228+
229+
Available since 5.40.0
230+
231+
</blockquote>
232+
227233
Returns a `[get, set]` pair of functions for working with context in a type-safe way.
228234

235+
`get` will throw an error if no parent component called `set`.
236+
229237
<div class="ts-block">
230238

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

376+
[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.
377+
368378
<div class="ts-block">
369379

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

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

515+
[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative.
516+
505517
<div class="ts-block">
506518

507519
```dts

0 commit comments

Comments
 (0)