Redux ds
Learn The Fundamentals of Redux
  •  

Displaying the State

PRO
Outline

A store has three functions that you're going to be using in this course:

  1. getState - fetches the current state of a store
  2. dispatch - fires off a new action
  3. subscribe - fires a callback everytime there's a new action after a reducer's action

We'll have the App component subscribe to the state using one of React's life-cycle hooks called componentWillMount(). This function is called when the component is going to be rendered, so it's a good place to put initialization logic.

We subscribe to the redux store and call React's setState() function every time the store changes so we always get the newly reduced state. React calls the render() function every time the component's state changes, which "renders" the component.

Update the App class to subscribe the store to React's setState function

src/index.js

class App extends React.Component {
  constructor() {
    super();
    this.state = {};
  }

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


render() {
[...]

Let's tweak the App component to display a checkbox whose state depends on the redux store.

Update render() to display a checkbox tied to Redux's state

src/index.js

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