repos / starfx

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

starfx / docs / posts
Eric Bower · 17 Aug 24

dispatch.md

 1---
 2title: Dispatch
 3description: How to activate controllers
 4---
 5
 6We use the term `dispatch` when we are emitting an event with a specific type
 7signature
 8([flux standard action](https://github.com/redux-utilities/flux-standard-action)).
 9
10There are two ways to activate a thunk: by dispatching an action or calling it
11within another thunk.
12
13The type signature of `dispatch`:
14
15```ts
16type Dispatch = (a: Action | Action[]) => any;
17```
18
19Within `starfx`, the `dispatch` function lives on the store.
20
21```ts
22const { createSchema, createStore } from "starfx";
23const [schema, initialState] = createSchema();
24const store = createStore({ initialState });
25
26store.dispatch({ type: "action", payload: {} });
27```
28
29# Dispatch in thunk
30
31```ts
32import { put } from "starfx";
33
34function* thunk(ctx, next) {
35  yield* put({ type: "click" });
36  yield* next();
37}
38```
39
40# Dispatch in react
41
42You can also use dispatch with a `react` hook:
43
44```tsx
45import { useDispatch } from "starfx/react";
46
47function App() {
48  const dispatch = useDispatch();
49
50  return <button onClick={() => dispatch({ type: "click" })}>Click me!</button>;
51}
52```
53
54# Listening to actions
55
56This is a pubsub system after all. How can we listen to action events?
57
58```ts
59import { take } from "starfx";
60
61function* watch() {
62  while (true) {
63    const action = yield* take("click");
64    // -or- const action = yield* take("*");
65    // -or- const action = yield* take((act) => act.type === "click");
66    // -or- const action = yield* take(["click", "me"]);
67    console.log(action.payload);
68  }
69}
70
71store.run(watch);
72```
73
74`watch` is what we call a [supervisor](/supervisors). Click that link to learn
75more about how they provide powerful flow control mechanisms.