Implementing Server Sorting
Introduction: The Need for Server-Side Sorting
Welcome back! In the previous lesson, you learned how to fetch and display catalog data in your React app using TanStack Query. Now, let’s take your catalog to the next level by adding server-side sorting.
Server-side sorting means that when a user wants to see the books sorted by title or author, your app will ask the server to send the data in the correct order. This is especially important when you have a lot of data because sorting on the server is faster and uses less memory on the user’s device. It also ensures that users always see the most up-to-date and accurate results.
By the end of this lesson, you will know how to let users sort the catalog by different fields and how to make your app request sorted data from the server.
How Server-Side Sorting Works
When you want to sort data, you have two main options:
- Client-side sorting: Fetch all the data, then sort it in the browser.
- Server-side sorting: Ask the server to sort the data before sending it.
For small datasets, client-side sorting is fine. But for larger catalogs, server-side sorting is better because:
- It reduces the amount of data sent to the client.
- It uses the server’s resources, which are usually more powerful.
- It ensures the user always sees the latest, most accurate data.
Regarding the amount of data being reduced — at first glance, sorting might seem like it only changes the order of items, so it’s not obvious why it would affect how much data is sent.
Consider a catalog with 10,000 books. If you perform client-side sorting, the server sends all 10,000 items to the browser, even if the user only needs to see the first 20.
With server-side sorting (usually combined with pagination), you can tell the server:
“Give me the first 20 books, sorted by title.”
The server sorts the entire dataset, then returns only those 20 items. This way, much less data travels over the network, making the app faster and more efficient.
To do server-side sorting, your app needs to send sorting instructions to the server. This is usually done by adding query parameters to the API request, such as sortBy=title and order=asc.
For example, a request might look like this:
This tells the server to return the books sorted by title in ascending order.
Adding Sorting Parameters to the API Call
