Skip to content

Commit 8221d4f

Browse files
Add top-level array store examples (#1518)
Add top-level array store examples to stores concept page Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 0ac6613 commit 8221d4f

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

src/routes/(0)concepts/(5)stores.mdx

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,50 @@ const [store, setStore] = createStore({
5959
});
6060
```
6161

62+
### Top-level array stores
63+
64+
While the examples above show a store as an object with properties, stores can also be arrays directly.
65+
When creating a top-level array store, the setter syntax differs slightly since you target indices directly rather than navigating through property keys first.
66+
67+
```jsx
68+
import { createStore } from "solid-js/store";
69+
70+
// Store as a top-level array
71+
const [users, setUsers] = createStore([
72+
{ id: 0, username: "felix909", location: "England", loggedIn: false },
73+
{ id: 1, username: "tracy634", location: "Canada", loggedIn: true },
74+
{ id: 2, username: "johny123", location: "India", loggedIn: true },
75+
]);
76+
```
77+
78+
To append a new item to a top-level array store, use the array's length as the index:
79+
80+
```jsx
81+
setUsers(users.length, {
82+
id: 3,
83+
username: "michael584",
84+
location: "Nigeria",
85+
loggedIn: false,
86+
});
87+
```
88+
89+
To modify an existing item by index:
90+
91+
```jsx
92+
// Update username of the first user
93+
setUsers(0, "username", "felix_updated");
94+
95+
// Update multiple properties at once
96+
setUsers(1, { location: "USA", loggedIn: false });
97+
```
98+
99+
You can also use filtering functions to update items based on conditions:
100+
101+
```jsx
102+
// Log out all users from Canada
103+
setUsers((user) => user.location === "Canada", "loggedIn", false);
104+
```
105+
62106
## Accessing store values
63107

64108
Store properties can be accessed directly from the state proxy through directly referencing the targeted property:

0 commit comments

Comments
 (0)