Pagination, Infinite Query and Mutations using React Query


Objectives

Learn how to implement Pagination, Infinite Scroll and Mutations using React Query.

Pagination

Pagination is a common technique used in user interfaces, particularly in web applications, to divide large amounts of content into smaller, more manageable chunks called pages. Instead of presenting all the content at once, pagination allows users to navigate through the content in a systematic and organized manner.

Pagination and Query Logic

  • queryKey: The queryKey is used to identify the query and is typically an array of values that uniquely represent the query.
  • queryFn: This is a function that defines how the data is fetched.
  • keepPreviousData: This option ensures that the previous data remains available while the new data is being fetched. It prevents the UI from flickering or becoming empty during the loading process.

Check out TanStack Query Documentation for more detail.

User Interface of the the post list

The browser should display something like this:

Infinite Query

Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. TanStack Query supports a useful version of useQuery called useInfiniteQuery for querying these types of lists. Checkout this page for more detail.

Infinite Query Logic

User Interface of the post list

The browser should display something like this:

Mutating Data

Here we use TodoList instead of PostList.

Let's walk through some key components:

  • Inside the TodoForm component, initialize a queryClient.
  • Use the useMutation hook to create a mutation function called addTodo, which will handle adding a new todo item.
  • Configure the addTodo mutation with a mutationFn that sends a POST request to "https://jsonplaceholder.typicode.com/todos" with the provided todo data and returns the response data.
  • Specify an onSuccess callback for the addTodo mutation, which updates the query data for the "todos" key and clears the input field.
  • Create a reference using the useRef hook, which will be used to access the input element.

Add test data to the list.

Display an error message when an error occurs.

Conclusion

React Query simplifies pagination, infinite querying, and mutations, which are common scenarios when working with user interfaces and retrieving data from an API.

Source