diff --git a/src/routes/reference/store-utilities/create-store.mdx b/src/routes/reference/store-utilities/create-store.mdx new file mode 100644 index 000000000..93524585a --- /dev/null +++ b/src/routes/reference/store-utilities/create-store.mdx @@ -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( + state: T | Store +): [get: Store, set: SetStoreFunction]; + +type Store = 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. diff --git a/src/routes/reference/store-utilities/data.json b/src/routes/reference/store-utilities/data.json index dd3522d84..c232a44c9 100644 --- a/src/routes/reference/store-utilities/data.json +++ b/src/routes/reference/store-utilities/data.json @@ -1,6 +1,7 @@ { "title": "Store Utilities", "pages": [ + "create-store.mdx", "produce.mdx", "reconcile.mdx", "unwrap.mdx",