To filter data based on an array of field values in Convex while using pagination, you can use the filter helper from the "convex-helpers" package along with pagination. This approach allows you to perform server-side filtering efficiently. Here's how you can achieve this:
- First, install the "convex-helpers" package if you haven't already:
npm install convex-helpers
- Then, in your Convex query function, you can use the
filter helper along with pagination like this:
import { filter } from "convex-helpers/server/filter";
export const filteredUsers = query({
args: {
selectedUsers: v.array(v.string()),
paginationOpts: paginationOptsValidator
},
handler: async (ctx, args) => {
return filter(
ctx.db.query("users"),
(user) => args.selectedUsers.includes(user.name)
).paginate(args.paginationOpts);
},
});
This query function will filter the users based on the selectedUsers array and return paginated results. The filter helper allows you to use TypeScript/JavaScript filtering logic directly in your query, which is then applied efficiently on the server side.
- On the client side, you can use the
usePaginatedQuery hook to fetch and paginate the filtered results:
import { usePaginatedQuery } from "convex/react";
function UserList() {
const selectedUsers = ["Bob", "Jane", "Jenny"];
const { results, status, loadMore } = usePaginatedQuery(
"filteredUsers",
{ selectedUsers, paginationOpts: { initialNumItems: 10 } }
);
}
This approach allows you to efficiently filter and paginate your data on the server side, improving performance for large datasets.
For more details on using complex filters and pagination in Convex, you can refer to these resources: