repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

commit
6334085
parent
dbb4ee1
author
Eric Bower
date
2024-08-17 01:37:49 +0000 UTC
docs: copy
1 files changed,  +52, -2
M docs/posts/store.md
+52, -2
 1@@ -123,13 +123,63 @@ store.run(function*() {
 2 The other methods are more generic and the user will have to provide types to
 3 them manually.
 4 
 5+# Updater function
 6+
 7+`schema.update` expects one or many state updater functions. An updater function
 8+receives the state as a function parameter. Any mutations to the `state`
 9+parameter will be applied to the app's state using
10+[immer](https://github.com/immerjs/immer).
11+
12+```ts
13+type StoreUpdater<S extends AnyState> = (s: S) => S | void;
14+```
15+
16+> It is highly recommended you read immer's doc on
17+> [update patterns](https://immerjs.github.io/immer/update-patterns) because
18+> there are limitations to understand.
19+
20+Here's a simple updater function that increments a counter:
21+
22+```ts
23+function* inc() {
24+  yield* schema.update((state) => {
25+    state.counter += 1;
26+  });
27+}
28+```
29+
30+Since the `update` function accepts an array, it's important to know that we
31+just run those functions by iterating through that array.
32+
33+In fact, our store's core state management can _essentially_ be reduced to this:
34+
35+```ts
36+import { produce } from "immer";
37+
38+function createStore(initialState = {}) {
39+  let state = initialState;
40+
41+  function update(updaters) {
42+    const nextState = produce(state, (draft) => {
43+      updaters.forEach((updater) => updater(draft));
44+    });
45+    state = nextState;
46+  }
47+
48+  return {
49+    getState: () => state,
50+    update,
51+  };
52+}
53+```
54+
55 # Updating state from view
56 
57 You cannot directly update state from the view, users can only manipulate state
58 from a thunk, endpoint, or a delimited continuation.
59 
60-This is a design decision that forces everything to route through our mini
61-controllers.
62+This is a design decision that forces everything to route through our
63+[controllers](/controllers).
64 
65 However, it is very easy to create a controller to do simple tasks like updating
66 state: