Writing a reducer

Then, after defining our actions, we need a reducer to process them. Of course, this also means that we have to define the shape of our state, and its initial value:

// Source file: src/counterApp/counter.reducer.js

/* @flow */

import { COUNTER_INCREMENT, COUNTER_RESET } from "./counter.actions";

import type { CounterAction } from "./counter.actions.js";

export const reducer = (
state = {
// initial state
count: 0,
clicks: 0
},
action: CounterAction
) => {
switch (action.type) {
case COUNTER_INCREMENT:
return {
count: state.count + action.value,
clicks: state.clicks + 1
};

case COUNTER_RESET:
return { count: 0, clicks: state.clicks + 1 };

default:
return state;
}
};

Our reducer is basically a switch statement; when the right type is found, a new state is returned. This pattern is very important, and key to Redux. We don't simply update the state, but rather we produce a new state object every time. We need a default case because actions are passed to all reducers (not in our case, since we have a single one), so it's possible that a reducer will ignore an action.

In our example, we have a single reducer and a single set of actions, so it can be argued that they could all be placed together in the same file, but that's not likely with most applications. Furthermore, if your state grows too large, check out combineReducers() at https://redux.js.org/api/combinereducers, and you'll be able to work in a more organized way, with multiple reducers and a store divided into logical pieces.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.193.232