setState - object form

Now we need a way of setting state. To do that, I’m going to make a few changes here. This should really be a button. This is kind of taking the shape of a button, so let’s change that now to be so. Now that has the nice appearance of a button. Let’s make this actually show the current number of claps with a clap emoji, so that we know that if we hit it, we’re going to get some clasp. That’s starting to look right. All buttons should have a type. This one is a button, not a submit or anything like that. So now we have our button. That seems to be right. It’s displaying this current number of claps. Unfortunately it’s not updating because we’re really just alerting the new button number, we’re not setting it. To set state we use a function called this.setState. It’s a magic functions that we get by extending React component. When we call it, we’re going to call it with the same shape of our component state, but we want to update it. Now again, I’m hard coding this value, but just to show you this simple form of, if I know the value that I want, I can pas it in in a new object that replaces this state, so there’s a nice symmetry there. This is the object form of a call to setState, so we’re calling setState with an object hta gets merges with this object, or in our cause is going to replace that zero with a hard coded one. It goes from zero to one, but no further. This is great when you know the exact state that you need to replace this state, but it’s not great when we want to update this from the previous state. Learn how to handle that next.

Play video: setState - object form
  1. Course overview
  2. Project setup
  3. ReactDOM.render and React.createElement
  4. JSX
  5. Functional components
  6. Props
  7. Class Components
  8. onClick and other events
  9. Component initial state
  10. 👉setState - object form
  11. setState - functional form
  12. Conditional rendering in JSX
  13. essential react 13
  14. Fetching pokeapi data
  15. componentDidMount
  16. setState and fetch
  17. Lists with Array.map()
  18. componentWillReceiveProps
  19. Component props
  20. Render props
  21. Separation of Concerns with components
  22. Higher-order components
  23. defaultProps
  24. Render prop actions
  25. Course summary