Skip to content

Commit 6238f9e

Browse files
authored
Clarify array appending methods in stores
1 parent 79af1ae commit 6238f9e

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/routes/concepts/stores.mdx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,9 @@ Instead of relying on discovering individual indices, path syntax introduces sev
253253

254254
### Appending new values
255255

256-
To append new values to an array in a store, use the setter function with the spread operator (`...`) to create a new array that includes the existing items and the new ones.
257-
For appending a single element, you can instead leverage the "path syntax" by specifying the array’s length as the index to set.
256+
To append values to an array in a store, use the setter function with the spread operator (`...`) or the path syntax. Both methods add an element to the array but differ in how they modify it and their reactivity behavior.
257+
258+
The spread operator creates a new array by copying existing elements and adding the new element, replacing the entire `store.users` array. This triggers reactivity for all effects tracking the array or its properties.
258259

259260
```jsx
260261
setStore("users", (otherUsers) => [
@@ -266,9 +267,11 @@ setStore("users", (otherUsers) => [
266267
loggedIn: false,
267268
},
268269
])
270+
```
269271

270-
// can become
272+
The path syntax appends the new element by setting it at the index equal to `store.users.length`, modifying the existing array. This triggers reactivity only for effects tracking the new index or properties like `store.users.length`, making it more efficient for targeted updates.
271273

274+
```jsx
272275
setStore("users", store.users.length, {
273276
id: 3,
274277
username: "michael584",

0 commit comments

Comments
 (0)