Redux ds
Learn The Fundamentals of Redux
  •  

Displaying the State

PRO

So great, now that you have a store, what do you do with it? A store has three functions that you're going to be using in this course: subscribe(), dispatch(), and getState(). getState() is simple, it just gets the current state of the store. dispatch() is the function you use to fire off a new action. subscribe() fires a callback every time a new action is fired after your reducer is done, so if you call getState() in the subscribe() callback you get the newly reduced state.

First off, let's make the App component subscribe to the state. The right place to do that is in the componentWillMount() function. This function is an example of what's known as a React component "life-cycle hook". The componentWillMount() function is important here because it gets called when the component is going to be created, so it's a good place to put initialization logic.

Let's subscribe to the redux store and call React's setState() function every time the store changes. React components also have their own internal state. React calls the render() function every time the component's state changes, and it's the render() function's job to tell React how to draw the component.

Subscribe the store to React's setState function
class App extends React.Component {
  constructor() {
    super();
    this.state = {};
  }

  componentWillMount() {
    store.subscribe(() => this.setState(store.getState()));
  }
}

Let's tweak the App component to display a checkbox whose state depends on the redux store. When the checked state is falsy, note that the checkbox is off. When you change checked to true by default, the checkbox is on.

Display a checkbox tied to Redux's state in the App component
render() {
  return (
    <div>
      <h1>To-dos</h1>
      <div>
        Learn Redux&nbsp;
        <input
          type="checkbox"
          checked={!!this.state.checked} />
      </div>
      {
        this.state.checked ? (<h2>Done!</h2>) : null
      }
    </div>
  );
}

What happens when you click on the checkbox? Absolutely nothing! What gives? One of the key ideas of React is that what gets displayed is a pure function of the component's state. In other words, since your state doesn't change, React will always render the checkbox as checked.

 

I finished! On to the next chapter