setState and fetch

The question for this lesson is “How do we communicate data that we’ve fetched from here into our render function?”. If you’re coming from the last lesson and you said setState, you are correct! We’ll use componentState to hold state between our life cycle events and our renders. First we need to setup an initial state. Again we’ll use a constructor for that. We always call super first, and then set up our instanced state. In this case, we’ll keep a character and by default it will be null. Now, let’s close our console, because we’re not going to log this out anymore. We are going to set it on state. So, once we get our pokemon, we want to call setState with it. setState lives on the component, so we call it through this, and we’re going to use that object form that we learned first because we know the whole value that we want to put in state, so we’ll say the new character is the one that we get from data. Now, in our render method, we should have that character on state, so we can use our curly braces to type a Javascript expression, which will be this.state.character, and let’s use the name. Now, we’re getting an error in our pokemon component. Now, I can tell you from experience that the reason is that we’re calling name on null. Before we get the pokemon, we’re trying to render this component, but there’s no name yet. Now, we can fix that by providing an initial value. That’s fine, but you can see how that could become cumbersome. So let’s take that back out and get the error again, get back in our error state. Now in our render function, we can decide what to render using a turnery. So if we have a pokemon on state, we’ll render the pokemon as we have defined here. However, if we don’t, let’s display a message like “loading...” to say that “Hey! Work is happening, but it may take a second”. Now, I’m checking for the wrong thing so this could take forever, so what we’re looking for is character. That’s what we put on state. Now without final, we get our character. Not that’s tiny, I’m going to bump that up. I’m going to use an h1. A proper heading for our pokemon.

Play video: setState and fetch
  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