Changing states with pure functions

In the previous section, we introduced the concept of the action and how that was the mediator through which we were allowed to change our state. We didn't change the state, though, in the normal sense of the word, but rather took the old state, applied the action, and produced a new state. To accomplish this, we need to use a pure function. In the context of Redux those are called reducers. Let's write ourselves a reducer:

// principles/first-reducer.js

module.exports = function reducer(state = {}, action) {
switch(action.type) {
case "SELECT_JEDI":
return Object.assign({}, action.payload);
default:
return state;
}
}

We highlight the pure aspect of the preceding reducer. It takes our selectedJedi from the action.payload, it copies it using the Object.assign(), assigns it, and returns the new state. 

What we have written is a reducer that switches, depending on the action we try to perform, and carries out the change. Let's put this pure function into use:

const reducer = require("./first-reducer");

let initialState = {};
let action = { type: "SELECT_JEDI", payload: { id: 1, name: "Jedi" } };
let state = reducer(initialState, action);
console.log(state);

/* this produces the following:
{ id: 1, name: 'Yoda' }
*/
..................Content has been hidden....................

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