Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a readOnly function to svelte/store #5872

Closed
wants to merge 1 commit into from
Closed
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
32 changes: 32 additions & 0 deletions site/content/docs/03-run-time.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,38 @@ const delayed = derived([a, b], ([$a, $b], set) => {
});
```


#### `readOnly`

```js
readable = readOnly(writable: Writable<T>)
```

---

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
Expand Down
11 changes: 11 additions & 0 deletions src/runtime/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,17 @@ export function derived<T>(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<T>(store: Writable<T>): Readable<T> {
return { subscribe: store.subscribe };
}

/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @param store readable
Expand Down