Create a custom hook to fetch remote data by passing a promise to the React 19 use
hook. Then render this data in Tanstack Table by memoizing the results and passing them to useReactTable
.
Transcript
[00:00] This table is nice, but it's rendering static data. Sometimes you need to fetch the data before you can render it. We're going to use the Pokey API to fetch remote data and then pass it to our table. So here we're going to take this index of Pokemon. We don't need all 1, 302 Pokemon.
[00:35] Just going to limit it to 30. Here we can see the type. So we have a count. We have the next URL for pagination. There's no previous URL.
[00:49] And then we have a name and the URL for the details of that Pokemon. So we'll copy that. In our editor, I'm going to create a file called usePokemon.tsx. Here I will declare a variable called const API URL. Cursor's already guessing what I want, but that's not quite it.
[01:27] I'm going to declare a Pokemon Promise. There we go. Pokemon promise. There we go. Instead of state, I'm going to use the new React use hook.
[01:46] So const data equals use Pokemon promise. Here We will import use from react. One other thing is I want to type this URL response. Right now, promise is returning an any. So, I'm going to go back to my browser, copy this.
[02:30] Could type this out manually, but I don't want to. Now I will prompt cursor and say, create a Pokemon response go. That looks about right, accept. And we'll go as promise Pokemon. So now this data will be of type Pokemon response.
[03:10] Inside of our app, we will cut all of this, move it into a component called const Key table equals return, paste it. Made a little copy paste error. So we'll worry about this component later. Here we'll create a temporary component function, pokedata. The temporary component function, PokeData.
[04:14] Oops. We'll use Pokemon. Here we will return a suspense boundary and pokedata. This will be a fallback of loading back in our browser. If we go to the network and disable cache, Here you can see a flash of loading and our data.
[04:52] So instead of rendering Poke data like this, we want to render our table. So inside of our Poke table, we will go const data equals usePokemon. Here We want to memoize the results of data. So we'll go results equals useMemo data.results. Here we'll go results.length.
[05:36] Data dot results. Here we'll go results dot length. We're getting a TypeScript error because the type of Pokemon does not match our column helpers. So we don't need this anymore. And delete that.
[05:58] We'll import type Pokemon. First we'll have to actually export it. Now in here, we can pass Pokemon. Now, TypeScript's going to help us out. Going to delete these.
[06:37] I'll change website to URL. And I'll delete these. So, copy PookieTable. We don't need initial state for website. We want initial state for URL.
[07:01] So Here, I'll delete this component, and now we're rendering the Poke table. We have a nice list of Pokemon.