Fetch and display row details with Promise.all in Tanstack Table

We map over the initial set of results then use Promise.all to efficiently fetch the details of each pokemon rendered in the table. This allows us to add more columns to our pokemon table.

Share with a coworker

Transcript

[00:00] Here we have a list of Pokemon names and their URLs, but this isn't very useful. Let's fetch the Pokemon details and display a little more information in each row. We'll open up this hook. For each Pokémon, there's a URL that we can fetch that will give us more details about that Pokémon. So in this promise, instead of just promise, instead of just returning the JSON, we will dot then and we'll call async data.

[00:46] It already kind of knows what we want. So it's returning, or it's calling promise.all and it's mapping on the results. It's fetching each Pokemon, getting the JSON for that Pokemon, and returning the data. Over in the API documentation, if we get a single Pokemon for Ditto, we want to pull off the height, the weight, the types, and one of the sprites. So we'll take the front default sprite.

[01:42] So in our code, instead of returning all the data, we will return Pokemon so that we know we have a name and URL. We'll return the image, height, weight, and the types. This is typed as any. Now we'll need to adjust our types a little bit. So the type that we are returning is the Pokemon.

[02:17] So we'll add this, but that is not this type. So we will add an internal type called Pokemon type. And we'll copy that, paste it over here. Right there. So the last thing we need to do is return data and results equals Pokemon.

[03:03] We need to bump that down. So if we go to our browser, and we go to our app, You can see that we're making a bunch of fetch calls for all of these Pokémon. We're not displaying any of that data yet. So let's go back to our column definitions. So over in our columns, we'll add an image.

[03:37] We'll add the image first so that it shows up as the first column. Next, After the name and before the URL, we'll add height, weight, and types. We've added a wrapper div to help center the text. So over in our browser, you can see that we have nice looking rows with Pokemon showing up. We can hide the columns.

[04:16] This changed when we changed our column types because tan stack table just maps over the type of columns that you have, so that updated automatically. One last thing we would want to do is, instead of estimating the size as 37, we would want to help the row virtualizer out and just estimate the size as 100.