Initial state and state helpers

Now let's look at the initial state of this component:

// The state of this component is consists of
// three properties: a collection of articles,
// a title, and a summary. The "fromJS()" call
// is used to build an "Immutable.js" Map. Also
// note that this isn't set directly as the component
// state - it's in a "data" property of the state -
// otherwise, state updates won't work as expected.
state = {
data: fromJS({
articles: [
{
id: cuid(),
title: 'Article 1',
summary: 'Article 1 Summary',
display: 'none'
},
{
id: cuid(),
title: 'Article 2',
summary: 'Article 2 Summary',
display: 'none'
},
{
id: cuid(),
title: 'Article 3',
summary: 'Article 3 Summary',
display: 'none'
},
{
id: cuid(),
title: 'Article 4',
summary: 'Article 4 Summary',
display: 'none'
}
],
title: '',
summary: ''
})
};

There are two interesting functions used to initialize the state. The first is cuid() from the cuid packageā€”a useful tool for generating unique IDs. The second is fromJS() from the immutable package. Here are the imports that pull in these two dependencies:

// Utility for constructing unique IDs... 
import cuid from 'cuid'; 
 
// For building immutable component states... 
import { fromJS } from 'immutable'; 

As the name suggests, the fromJS() function is used to construct an immutable data structure. Immutable.js has very useful functionality for manipulating the state of React components. You'll be using Immutable.js throughout the remainder of the book, and you'll learn more of the specifics as you go, starting with this example.

For a more in-depth look at Immutable.js, check out Mastering Immutable.js: https://www.packtpub.com/web-development/mastering-immutablejs

You may remember from the previous chapter that the setState() method only works with plain objects. Well, Immutable.js objects aren't plain objects. If we want to use immutable data, you need to wrap them in a plain object. Let's implement a helper getter and setter for this:

// Getter for "Immutable.js" state data... 
get data() { 
  return this.state.data; 
} 
 
// Setter for "Immutable.js" state data... 
set data(data) { 
  this.setState({ data }); 
} 

Now, you can use your immutable component state inside of our event handlers.

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

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