Merging all reducers together

OK, so we now have a reducer for handling our list of jedis as well as a reducer dedicated to handling selections of a specific jedis. We mentioned before that, in Redux, we have a single store where all our data lives. Now it's time to create that single store. This can be easily accomplished by creating the following function store():

// core-concepts/merged-reducers.js

function store(state = { jedis: [], selectedJedi: null }, action) {
return {
jedis: jediListReducer(state.jedis, action),
selectedJedi: selectJediReducer(state.selectedJedi, action)
};
}

let newJediActionYoda = { type: "ADD_ITEM", payload: { name: "Yoda"} };
let newJediActionVader = { type: "ADD_ITEM", payload: { name: "Vader"} };
let newJediSelection = { type: "SELECT_JEDI", payload: { name: "Yoda"} };

let initialState = { jedis: [], selectedJedi: {} };

let state = store(initialState, newJediActionYoda);
console.log("Merged reducers", state);
/*
{
jedis: [{ name: 'Yoda' }],
selectedJedi: {}
}
*/

state = store(state, newJediActionVader);
console.log("Merged reducers", state);
/*
{
jedis: [{ name 'Yoda' }, {name: 'Vader'}],
selectedJedi: {}
}
*/

state = store(state, newJediSelection);
console.log("Merged reducers", state);

console.log(state);
/*
{
jedis: [{ name: 'Yoda' }, { name: 'Vader'}],
selectedJedi: { name: 'Yoda' }
}
*/

From what we can see here, our store() function does nothing more than return an object. The returned object is our current state. What we choose to call the properties of the state object is what we want to refer to when displaying the content of the store. If we want to change the state of our store, we need to invoke the store() function anew and provide it with an action that represents the intent of our change.

..................Content has been hidden....................

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