You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: www/src/content/docs/store.mdx
+123-1Lines changed: 123 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -287,13 +287,87 @@ export default function Page() {
287
287
}
288
288
```
289
289
290
+
## Middleware
291
+
292
+
You may need to run some code that's separate from your application lifecycle when a store updates. This includes persisting to local storage or logging updates to the console. You may also need to monitor and manipulate the store's value directly, as in developer tooling or integration with state management solutions like Immer.
293
+
294
+
For each of these, you can reach for middleware. This lets you hook into the store's lifecycle, meaning whenever a value is set, and whenever the store is initialized.
295
+
296
+
### Built-in logger middleware
297
+
298
+
To use the built-in logger middleware, pass `loggerMiddleware` in the `middleware` array when creating the store:
299
+
300
+
```ts
301
+
import { loggerMiddleware, store } from"@simplestack/store";
This example shows how to implement a custom middleware that persists to `localStorage`.
309
+
310
+
You can import the `StoreMiddleware` type from `@simplestack/store` to create your own middleware. For this use case, you can use the `set` property to wrap the `set()` call and persist the store's value:
You will also want to check for existing values in `localStorage` and initialize the store with them if they exist. To do this, you can use the `init` property to run code when the store is initialized:
Middleware can wrap `set()` and/or run initialization logic. This is useful when you need to log updates, persist data, or wire in side effects. Use `set` to wrap updates, and `init` for startup work that can optionally return a cleanup function.
-`set(setter: Setter<T>): void` - Set the value directly or by using a function that receives the current state.
407
528
-`subscribe(callback: (state: T) => void): () => void` - Subscribe with a callback. Returns an unsubscribe function.
408
529
-`select(...path: (string | number | symbol)[]): Store<...>` (present only when `T` is an object or array) - Select one or more keys/indices. Returns a nested Store (type inferred from the path).
409
530
-`getInitial(): T` - Get the initial state the store was created with. Used internally for SSR resume-ability.
531
+
-`destroy(): void` - Run cleanup from middleware `init()` hooks.
0 commit comments