createStore
Creates a store with an initial state and actions that can modify the state.
const store = createStore(config);Parameters
Section titled “Parameters”config- The configuration for the store.
Returns
Section titled “Returns”The created store with state management methods.
get- Returns the current state of the store.actions- Actions that can modify the state of the store.subscribe- Subscribes to changes in the state of the store. Returns an unsubscribe function.
Configuration
Section titled “Configuration”The config object can contain the following properties:
Setup
initialState- The initial state of the store.actions- A function that defines actions that can modify the state.
Lifecycle hooks
onLoad?- Invoked when the store is created.onAttach?- Invoked when the store is subscribed to.onDetach?- Invoked when the store is unsubscribed from.onChange?- Invoked whenever the state changes.
Persistence
persist?- Whether to persist the state of the store.key?- The unique key used to identify this store in storage. Required ifpersistis true.storage?- The storage to use for persisting the state. Defaults to local storage if available.serializer?- The serializer to use for storing the state. Defaults to JSON.
Basic example
Section titled “Basic example”import { createStore } from "dharma-core";
const store = createStore({ initialState: { count: 0 }, actions: ({ set }) => ({ increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }),});Lifecycle hooks
Section titled “Lifecycle hooks”import { createStore } from "dharma-core";import { State } from "./types";
const initialState: State = { data: null, loading: true, error: null };const store = createStore({ initialState, onAttach: async ({ set }) => { try { const response = await fetch("https://api.example.com/data"); const data = await response.json(); set({ data, loading: false }); } catch (error) { set({ error, loading: false }); } }, onDetach: ({ reset }) => reset(),});Persisting state
Section titled “Persisting state”import { createStore } from "dharma-core";
const store = createStore({ persist: true, key: "count", initialState: { count: 0 }, actions: ({ set }) => ({ increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }),});Custom storage and serializer
Section titled “Custom storage and serializer”import { createStore } from "dharma-core";import superjson from "superjson";
const store = createStore({ persist: true, key: "count", storage: sessionStorage, serializer: superjson, initialState: { count: 0 }, actions: ({ set }) => ({ increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), }),});