Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Augment React Resource JSON with Custom Properties

    reactReact
    ^0.0.0-experimental-b53ea6ca0

    You're never stuck with the data you get from the server.
    The Pokeapi doesn't have an id property on Pokemon but we can transform our response to include exactly what we need.

    With a little destructuring assignment and object spread we can augment our API with helpful properties

    Code

    Code

    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: We had to do a really gross thing to get an ID out of this Pokemon. In an ideal world, this API would have an ID, but it doesn't, so we had to make our own. This is a bad place to keep it. I don't want anyone else to copy this code or to try to make this work on their own.

    Instead, we can augment our resource so that it has an ID. Now, if I save it, you can see how this app breaks spectacularly. Couldn't catch them all. Let's open our tree view, jump into API, and fix this problem at the right level.

    Here we have our fetchPokemon collection function, which fetches the collection at this URL, turns it to JSON. Then we have a couple sleeps so we can see all of the transitions happen. We can chain an additional then here to modify the response.

    We start by just taking a response and returning a response. That works. To modify our response, we can return an object that we spread the response out on. Now, anytime we use an arrow function and we want to return an object, we have to wrap it in these parens. Otherwise, JavaScript thinks this is a block and gets all kinds of confused.

    We can then customize certain properties. The one that we want to customize is results. We'll start by making that response.results and we'll map. Now we have a chance for each Pokemon to modify the Pokemon just a little bit. Start by returning the same Pokemon. Then again, with the parens, the objects, the spreading, and closing it up. It formatted, so, so far, so good.

    Finally, we'll want to add an ID. Then using that same code that we had before, Pokemon.url.split//, and then take the sixth element. Format, which means our code's good. Save and see if it works.

    Excellent. Now we have IDs baked into our resource, and we don't have to do any cringey stuff at the app level. We can just use ID directly.