You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
console.log(description.get()); // "New description"
30
31
```
31
32
33
+
If you need to select a nested value, you can pass the complete object path as arguments to the `select()` function like so. This works for both object keys and array indices:
34
+
35
+
```tsx
36
+
const tags =documentStore.select("meta", "tags");
37
+
```
38
+
32
39
## Installation
33
40
34
41
Install the dependency from npm:
@@ -149,18 +156,27 @@ function setTheme(theme: string) {
149
156
150
157
However, this is fairly verbose and error-prone. Instead, you can create "sub-stores" by calling `select('key')` on the parent store, where `key` is the object key or array index you want to select. This creates a new store instance that lets you operate on the selected object key.
151
158
152
-
In this example, we can create a sub-store for the theme preference:
159
+
In this example, we can create a sub-store for the `preference` key, and operate on the `theme` value:
Then, you can update the user's theme preference by calling `set()` on the sub-store directly:
164
180
165
181
```tsx ins={6} del={2-5}
166
182
function setTheme(theme:string) {
@@ -174,6 +190,10 @@ function setTheme(theme: string) {
174
190
175
191
Changes to `themeStore` automatically update `userStore`, and vice versa.
176
192
193
+
:::info
194
+
If a `select()` path crosses a potentially undefined value at runtime (for example, `preferences` is missing), `set()` is discarded for safety and a warning is logged in dev mode.
195
+
:::
196
+
177
197
You can then subscribe to a sub-store the same way you subscribe to a parent store. Pass the sub-store to the `useStoreValue` hook:
178
198
179
199
<TabssyncKey="framework">
@@ -385,5 +405,5 @@ These types are exported for TypeScript users.
385
405
-`get(): T` - Get the current value of the store.
386
406
-`set(setter: Setter<T>): void` - Set the value directly or by using a function that receives the current state.
387
407
-`subscribe(callback: (state: T) => void): () => void` - Subscribe with a callback. Returns an unsubscribe function.
388
-
-`select(key: K): Store<SelectValue<T, K>>` (present only when `T` is an object or array) - Select a key or array index of the store. Returns a nested Store.
408
+
-`select(...path: (string | number | symbol)[]): Store<...>` (present only when `T` is an object or array) - Select one or more keys/indices. Returns a nested Store (type inferred from the path).
389
409
-`getInitial(): T` - Get the initial state the store was created with. Used internally for SSR resume-ability.
0 commit comments