Dispatcher are async functions that receive a and, in addition some arguments that will be passed to the reducer. This the one way to modify the store. Like react.setStatedispatch is async. Use await keyword to make things after a dispatch. There is 2 ways to dispatch:
Using the method direclty
Calling a dispatcher created by or
Dispatching will trigger and will rerender all connected components that are wrapped by the HOC of a same RxStore instance (think singleton).
asyncdispatch(reducer)
Using dispatch method directly. Be aware with this method. It can generate a lot of boilerplate code. To reduce it, see
Example
todo.reducers.js
import {createTodo} from './todo.utils.js';
export function addTodo(state, todo){
return {
...state, // We don't mutate the state. We create a copy.
todos: state.todos.concat(createTodo(todo))
}
}
todo.addInput.container.jsx
import { addTodo } from './todo.reducers.js';
import todoStore from './todo.store.js';
export default function AddInput(){
return <input type='text' onBlur={(e) => todoStore.dispatch(addTodo, e.target.value)};
}
createDispatcher(reducer, ...rest)
createDispatcher is more like a built-in helper to reduce repetitive code around dispatch;
Example
todo.reducers.js
import {createTodo} from './todo.utils.js';
export function addTodo(state, todo){
return {
...state, // We don't mutate the state. We create a copy.
todos: state.todos.concat(createTodo(todo))
}
}
todo.dispatchers.js
import { addTodo } from './todo.reducers.js';
import todoStore from './todo.store.js';
export const handleTodoAdd = todoStore.createDispatcher(addTodo); // equivalent at (todo) => todoStore.dispatch(addTodo, todo);
todo.addInput.container.jsx
import { handleAddTodo } from './todo.dispatchers.js';
export default function AddInput(){
return <input type='text' onBlur={(e) => handleAddTodo(e.target.value)};
}
createDispatchers is more like a built-in helper to reduce repetitive code around createDispatcher.
Example
todo.reducers.js
import {createTodo} from './todo.utils.js';
export function addTodo(state, todo){
return {
...state, // We don't mutate the state. We create a copy.
todos: state.todos.concat(createTodo(todo))
}
}
export function ...
todo.addInput.container.jsx
import todoStore from './todo.store.js';
import * as todoReducers from './todo.reducers.js';
const { addTodo: handleAddTodo } = todoStore.createDispatchers(todoReducers);
export default function AddInput(){
return <input type='text' onBlur={(e) => handleAddTodo(e.target.value)};
}