Dispatch
How to activate controllers
We use the term dispatch
when we are emitting an event with a specific type
signature
(flux standard action).
There are two ways to activate a thunk: by dispatching an action or calling it within another thunk.
The type signature of dispatch
:
1type Dispatch = (a: Action | Action[]) => any;
Within starfx
, the dispatch
function lives on the store.
1const { createSchema, createStore } from "starfx";
2const [schema, initialState] = createSchema();
3const store = createStore({ initialState });
4
5store.dispatch({ type: "action", payload: {} });
Dispatch in thunk #
1import { put } from "starfx";
2
3function* thunk(ctx, next) {
4 yield* put({ type: "click" });
5 yield* next();
6}
Dispatch in react #
You can also use dispatch with a react
hook:
1import { useDispatch } from "starfx/react";
2
3function App() {
4 const dispatch = useDispatch();
5
6 return <button onClick={() => dispatch({ type: "click" })}>Click me!</button>;
7}
Listening to actions #
This is a pubsub system after all. How can we listen to action events?
1import { take } from "starfx";
2
3function* watch() {
4 while (true) {
5 const action = yield* take("click");
6 // -or- const action = yield* take("*");
7 // -or- const action = yield* take((act) => act.type === "click");
8 // -or- const action = yield* take(["click", "me"]);
9 console.log(action.payload);
10 }
11}
12
13store.run(watch);
watch
is what we call a supervisor. Click that link to learn
more about how they provide powerful flow control mechanisms.