Fetch and render paginated data with React 19 use

Fetch paginated data with React 19 use. Set a promise as the initial value in useState then return a function from your custom hook to update that promise with a new one to load the next page of data.

Share with a coworker

Transcript

[00:00] We are fetching the first page of data. We're limiting the amount of items to come back to 30, and the offset is 0. We can make this dynamic by creating a function that returns the Pokemon promise and dynamically changing that promise inside of this hook. So the first thing we'll do is we'll take this limit and offset off. So now we just have the base API URL.

[00:40] We will make this a function. It will accept an offset number. Now we'll wrap this in a template string And we'll go limit is 30, offset is the variable, we'll return the JSON, and then we get all of the Pokemon. So now This is not Pokemon Promise, this is Fetch Pokemon. We can kick off our first promise by going const Pokemon Promise equals Fetch Pokemon and then zero.

[01:34] Now, when we go to our browser, everything should still work the same, and it does. When we go back to our hook to change this promise, we need to introduce const promise and set promise. We'll Import useState from React. Now we will use the promise. Kind of like useState, instead of returning an object like this, we're going to return an array, and we'll return a function like this.

[02:27] And instead of just passing the offset, we want, we'll call this page. And we will do page times 30. Data is an array. So we'll get, we'll destructure data off of usePokemon and we'll go FetchPokemonPage as const. That will resolve the TypeScript error.

[03:13] This data variable is the Pokemon response, and fetchPokemonPage is the function that returns the fetcher. Down in our render method, we're going to create a button. We'll call fetchPage, but first we'll need a new useState variable to keep track of the page that we're on. So we'll initialize it to 0, and every time we click, this fetchPage function will fire. We will set const new page equals page plus one.

[03:58] We'll set the page and we'll fetch the Pokemon page. Now in our browser, we can fetch page one, and then we can fetch page two, and we can paginate all the way through the data that the Pokemon API gives us. In review, we had to create a function that called our fetch to the Pokemon API. The fetch just returned the same data that we were mapping over anyways. Now that fetchPokemon is a function, we have to create the initial promise above usePokemon.

[04:42] This will kick off the promise, and it will start resolving when this file loads in the browser. The first page is our initial data and we will use that data and then we return a function that will set the promise to a new Pokemon promise.