diff --git a/site/content/docs/03-run-time.md b/site/content/docs/03-run-time.md index 5bcbe8764c29..8d9c7c8e0a40 100644 --- a/site/content/docs/03-run-time.md +++ b/site/content/docs/03-run-time.md @@ -365,6 +365,38 @@ const delayed = derived([a, b], ([$a, $b], set) => { }); ``` + +#### `readOnly` + +```js +readable = readOnly(writable: Writable) +``` + +--- + +Sometimes readable and derived aren't the ideal tools for more complex custom stores. For stores that need to only be writable in their module, and _not_ outside, you can use `readOnly` to get a readonly version of a writable store. + +```js +import { writable, readOnly } from 'svelte/store'; + +const userStore = writable({}); + +export function logIn(username, password) { + if (password == 'password') { + userStore.set({ username, error: null }); + } else { + userStore.set({ username: null, error: 'Bad Password' }); + } +} + +export function logOut() { + userStore.set({}); +} + +export const user = readOnly(userStore); +``` + + #### `get` ```js diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index 64a63d417967..0e7bcc847cea 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -196,6 +196,17 @@ export function derived(stores: Stores, fn: Function, initial_value?: T): Rea }); } +/** + * Get a readable store from a writable store. + * + * @param store writable + * + * @returns readable store + */ +export function readOnly(store: Writable): Readable { + return { subscribe: store.subscribe }; +} + /** * Get the current value from a store by subscribing and immediately unsubscribing. * @param store readable