Skip to content

Commit 4f4ca84

Browse files
authored
Docs(stores): Add callout and example for nested stores (#905)
1 parent 3032bd3 commit 4f4ca84

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/routes/concepts/stores.mdx

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,33 @@ Separating the read and write capabilities of a store provides a valuable debugg
198198

199199
This separation facilitates the tracking and control of the components that are accessing or changing the values.
200200
</Callout>
201+
<Callout type="advanced">
202+
A little hidden feature of stores is that you can also create nested stores to help with setting nested properties.
203+
204+
```jsx
205+
const [store, setStore] = createStore({
206+
userCount: 3,
207+
users: [ ... ],
208+
})
209+
210+
const [users, setUsers] = createStore(store.users)
211+
212+
setUsers((currentUsers) => [
213+
...currentUsers,
214+
{
215+
id: 3,
216+
username: "michael584",
217+
location: "Nigeria",
218+
loggedIn: false,
219+
},
220+
])
221+
222+
```
223+
Changes made through `setUsers` will update the `store.users` property and reading `users` from this derived store will also be in sync with the values from `store.users`.
224+
225+
Note that the above relies on `store.users` to be set already in the existing store.
226+
227+
</Callout>
201228

202229
## Path syntax flexibility
203230

@@ -260,9 +287,11 @@ setStore("users", [1, 3], "loggedIn", false)
260287
```
261288

262289
<Callout>
263-
If your *store* is array, you can specify a range of indices using an object with `from` and `to` keys.
290+
If your *store* is an array, you can specify a range of indices using an object with `from` and `to` keys.
264291

265292
```jsx
293+
const [store, setStore] = createStore([]) // A store that is an array
294+
...
266295
setStore({ from: 1, to: store.length - 1 }, "loggedIn", false)
267296
```
268297

0 commit comments

Comments
 (0)