- counter
- toggle
- value
- set-simple
- task-simple
- list
State structure
type CounterState = number;
// counter state example
5; // :-)
import React, { useReducer } from "react";
import { createReducer } from "power-reducers/counter";
const [counterReducer, { getInitialState }] = createReducer({
initial: 0,
incrementOn: 'INCREMENT',
incrementByOn: {
type: 'INCREMENT_BY',
payload: 'delta' // read data from action.delta
},
decrementOn: 'DECREMENT',
_customHandlers: [{
type: 'DOUBLE',
handler: (state = 0) => state * 2
}
});
export const Counter: React.SFC<{}> = () => {
const [counterState, dispatch] = useReducer(
counterReducer,
getInitialState() // required for hook
);
function doIncrement() {
dispatch({ type: "INCREMENT" });
}
function doDecrement() {
dispatch({ type: "DECREMENT" });
}
function doIncrementBy10() {
dispatch({ type: "INCREMENT_BY", payload: 10 });
}
function doDouble() {
dispatch({ type: "DOUBLE" });
}
return (
<>
<p>Count: {state}</p>
<button onClick={doIncrement}>+ 1</button>
<button onClick={doDecrement}>- 1</button>
<button onClick={doDouble}>x 2</button>
<button onClick={doIncrementBy10}>+ 10</button>
</>
);
}
[
reducerFunction, // (state, action) => newState
{
getInitialState, // () => initialCounterState
generateState // (value: number) => counterState
}
] = createReducer(/* ... */);
Initial/default state value.
type: number
default: 0
What action(s) will +1
// action example:
{ type: "INCREMENT", ... }
What action(s) will -1
// action example:
{ type: "DECREMENT", ... }
What action(s) will increment by provided value
// action example:
{ type: "INCREMENT_BY", payload: 5 }
What action(s) will decrement by provided value
// action example:
{ type: "DECREMENT_BY", payload: 5 }
What action(s) will set value
// action example:
{ type: "SET_COUNTER", payload: 5 }
What action(s) will set value that was set as initial
// action example:
{ type: "RESET_COUNTER", ... }
What action(s) will set value to 0 (zero)
// action example:
{ type: "SET_ZERO", ... }
Create own reducers for different action(s) types (try to avoid this).
Example
createReducer({
// ...
_customHandlers: [
{
type: "DOUBLE_COUNT",
handler: (state, action) => {
// executed when action.type === "DOUBLE_COUNT"
return state * 2;
}
}
]
});
1 type HandlerOption - single item or Array containing the following types (can be mixed):
Parameter example | Valid action example |
---|---|
"SET_VALUE" |
{ type: "SET_VALUE", payload: /* some data */ } |
{ type: "SET_VALUE" } |
{ type: "SET_VALUE", payload: /* some data */ } |
{ type: "INCREMENT_BY", payload: "diff" } |
{ type: "INCREMENT_BY", diff: /* some data */ } |
{ type: "INCREMENT_BY", payload: (action) => someData |
{ type: "INCREMENT_BY", /* data to be resolved */ } |