Previously, we looked at ways to display tabular data on a webpage. Let’s pick up where we left off, but with more data. The last time, the data was hard-coded into an array. This time, let’s use Axios to load some fake data from JSONPlaceholder.
In the above example, we added a little “Page X of Y” control to the upper right-hand corner of the page and computed values of paginatedResults, numberOfResults, and lastPage to drive the thing. There are also values for currentPage and resultsPerPage. The problem is that if you can’t divide numberOfResults evenly by resultsPerPage, stuff breaks. Also, if you filter your results, you will get a RangeError: Invalid array length error (because the number of results changes).
So, how do we fix it? Let’s start by simplifying the example.
In this example, I removed the sorting and querying bits to make what’s going on a little more clear. I then changed the resultsPerPage from 20 to 15. With the same 200 results from the api, that makes the number of pages 13.333333. If we wrap the formula in Math.ceil(), that should round the result up to 14, allowing you to properly show that final page of results. It should also deal with that RangeError: Invalid array length error.
Let’s bring back in the sorting and querying, now.
Now that pagination is working, I need to find something else to better this table. Have a suggestion? Feel free to drop it in the comments, below.