Read-only states

We want to ensure we only have one way to alter state, and that is through mediators called actions. An action should describe the intent of the action as well as the data that should be applied to the current state. An action is dispatched by us using a store.dispatch(action). The action itself should look like the following:

// principles/action.js

// the action
let action = {
// expresses intent, loading jedis
type: "LOAD_JEDIS",
payload:[
{ name: "Yoda", id: 1 },
{ name: "Palpatine", id: 2 },
{ name: "Darth Vader", id: 3 }
]
};

At this point, let's try to implement what a store might actually look like and what it initially contains:

// principles/storeII.js

class Store {
constructor() {
this.state = {
jedis: [],
selectedJedi: null
}
}

getState() {
return this.state;
}
}

const store = new Store();

console.log(store.getState());
// state should now be
/*
{
jedis : [],
selectedJedi: null
}
*/

We can see that it is an object that consists of two properties, jedis, which is an array, and selectedJedi, which is an object holding an object that we select. At this point, we want to dispatch an action, which means we will take our old state, as shown in the preceding code, and produce a new state. The action we described earlier should change the jedis array and replace the empty array with the incoming array. Remember, though, we don't mutate the existing store object; we simply take it, apply our change, and produce a new object. Let's dispatch our action and see the end result:

// principles/storeII-with-dispatch.js

class Store {
constructor() {
this.state = {
jedis: [],
selectedJedi: null
}
}

getState() {
return this.state;
}

dispatch(action) {
// to be implemented in later sections
}
}

// the action
let action = {
type: 'LOAD_JEDIS',
payload:[
{ name: 'Yoda', id: 1 },
{ name: 'Palpatine', id: 2 },
{ name: 'Darth Vader', id: 3 }
]
}

// dispatching the action, producing a new state
store.dispatch(action);

console.log(store.getState());
// state should now be
/*
{
jedis : [
{ name: 'Yoda', id: 1 },
{ name: 'Palpatine', id: 2 },
{ name: 'Darth Vader', id: 3 }
],
selectedJedi: null
}
*/

The preceding code is pseudo code as it doesn't actually produce the intended result, yet. We will learn to implement a store in later chapters. OK, so now our state has changed and our incoming array has replaced the empty array we used to have. We again repeat that we have not mutated the existing state, but instead produced a new state given the old state and our action. Let's look at the next section on pure functions and further explain what we mean.

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

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