Skip to content

Commit d885ae3

Browse files
authored
add createStore to /reference (#694)
1 parent 548bbce commit d885ae3

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
---
2+
title: createStore
3+
---
4+
5+
Stores were intentionally designed to manage data structures like objects and arrays but are capable of handling other data types, such as strings and numbers.
6+
7+
## Types Signature
8+
9+
```tsx
10+
import { createStore } from "solid-js/store";
11+
import type { StoreNode, Store, SetStoreFunction } from "solid-js/store";
12+
13+
function createStore<T extends StoreNode>(
14+
state: T | Store<T>
15+
): [get: Store<T>, set: SetStoreFunction<T>];
16+
17+
type Store<T> = T; // conceptually readonly, but not typed as such
18+
```
19+
20+
## Usage
21+
22+
```tsx
23+
import { createStore } from "solid-js/store";
24+
25+
// Initialize store
26+
const [store, setStore] = createStore({
27+
userCount: 3,
28+
users: [
29+
{
30+
id: 0,
31+
username: "felix909",
32+
location: "England",
33+
loggedIn: false,
34+
},
35+
{
36+
id: 1,
37+
username: "tracy634",
38+
location: "Canada",
39+
loggedIn: true,
40+
},
41+
{
42+
id: 1,
43+
username: "johny123",
44+
location: "India",
45+
loggedIn: true,
46+
},
47+
],
48+
});
49+
```
50+
51+
## Getter
52+
53+
Store objects support the use of getters to store derived values.
54+
55+
```tsx
56+
const [state, setState] = createStore({
57+
user: {
58+
firstName: "John",
59+
lastName: "Smith",
60+
get fullName() {
61+
return `${this.firstName} ${this.lastName}`;
62+
},
63+
},
64+
});
65+
```
66+
67+
## Setter
68+
69+
Changes can take the form of function that passes previous state and returns new state or a value.
70+
Objects are always shallowly merged. Set values to undefined to delete them from the Store.
71+
In TypeScript, you can delete a value by using a non-null assertion, like `undefined!`.
72+
73+
```tsx
74+
const [state, setState] = createStore({
75+
firstName: "John",
76+
lastName: "Miller",
77+
});
78+
79+
setState({ firstName: "Johnny", middleName: "Lee" });
80+
// ({ firstName: 'Johnny', middleName: 'Lee', lastName: 'Miller' })
81+
82+
setState((state) => ({ preferredName: state.firstName, lastName: "Milner" }));
83+
// ({ firstName: 'Johnny', preferredName: 'Johnny', middleName: 'Lee', lastName: 'Milner' })
84+
```
85+
86+
---
87+
88+
To learn more about using stores check the [Stores Guide](/concepts/stores), and the **Store Utilities** section for more advanced APIs.

src/routes/reference/store-utilities/data.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"title": "Store Utilities",
33
"pages": [
4+
"create-store.mdx",
45
"produce.mdx",
56
"reconcile.mdx",
67
"unwrap.mdx",

0 commit comments

Comments
 (0)