Creating a store implementation

We have yet to create the dispatch() method, so we will do that next:

// dataflow/redux.js

export function dispatch(action) {
// implement this
}

What we can see from the preceding code is that we have a dispatch() function, which is one of the things we export from this file. Let's try to fill in the implementation:

// dataflow/redux-stepI.js

// 1)
function itemsReducer(state = [], action) {
switch(action.type) {
case "CREATE_ITEM":
return [...state, Object.assign(action.payload) ];
default:
return state;
}
}

// 2)
let state = {
items: []
};

// 3
function store(state = { items: [] }, action) {
return {
items: itemsReducer(state.items, action)
};
}

// 4)
export function getState() {
return state;
}

// 5)
export function dispatch(action) {
state = store(state, action);
}

Let's explain what we did there from the top. We first define a reducer 1) called itemsReducer,  which can produce a new state given a new item. Thereafter, we create a state variable, which is our state 2). This is followed by the store() function 3), which is a function to set up which property goes together with which reducer. Thereafter, we define a function called getState() 4), which returns our current state. Lastly, we have our dispatch() function 5), which just invokes the store() function with the action we provide it.

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

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