Skip to content

Commit

Permalink
add createStore to /reference (#694)
Browse files Browse the repository at this point in the history
  • Loading branch information
atilafassina authored Apr 23, 2024
1 parent 548bbce commit d885ae3
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
88 changes: 88 additions & 0 deletions src/routes/reference/store-utilities/create-store.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
title: createStore
---

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.

## Types Signature

```tsx
import { createStore } from "solid-js/store";
import type { StoreNode, Store, SetStoreFunction } from "solid-js/store";

function createStore<T extends StoreNode>(
state: T | Store<T>
): [get: Store<T>, set: SetStoreFunction<T>];

type Store<T> = T; // conceptually readonly, but not typed as such
```

## Usage

```tsx
import { createStore } from "solid-js/store";

// Initialize store
const [store, setStore] = createStore({
userCount: 3,
users: [
{
id: 0,
username: "felix909",
location: "England",
loggedIn: false,
},
{
id: 1,
username: "tracy634",
location: "Canada",
loggedIn: true,
},
{
id: 1,
username: "johny123",
location: "India",
loggedIn: true,
},
],
});
```

## Getter

Store objects support the use of getters to store derived values.

```tsx
const [state, setState] = createStore({
user: {
firstName: "John",
lastName: "Smith",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
},
});
```

## Setter

Changes can take the form of function that passes previous state and returns new state or a value.
Objects are always shallowly merged. Set values to undefined to delete them from the Store.
In TypeScript, you can delete a value by using a non-null assertion, like `undefined!`.

```tsx
const [state, setState] = createStore({
firstName: "John",
lastName: "Miller",
});

setState({ firstName: "Johnny", middleName: "Lee" });
// ({ firstName: 'Johnny', middleName: 'Lee', lastName: 'Miller' })

setState((state) => ({ preferredName: state.firstName, lastName: "Milner" }));
// ({ firstName: 'Johnny', preferredName: 'Johnny', middleName: 'Lee', lastName: 'Milner' })
```

---

To learn more about using stores check the [Stores Guide](/concepts/stores), and the **Store Utilities** section for more advanced APIs.
1 change: 1 addition & 0 deletions src/routes/reference/store-utilities/data.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"title": "Store Utilities",
"pages": [
"create-store.mdx",
"produce.mdx",
"reconcile.mdx",
"unwrap.mdx",
Expand Down

0 comments on commit d885ae3

Please sign in to comment.