learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->setState and fetch

Essetial React

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.



Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.