Skip to content

Commit

Permalink
feat: pre-fetching logic (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
prathameshbelurkar committed Jun 24, 2024
1 parent 1521057 commit 3ae195e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
21 changes: 20 additions & 1 deletion src/features/bookings/useBookings.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { useSearchParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useQuery, useQueryClient } from "@tanstack/react-query";

import { getBookings } from "../../services/apiBookings";

import { PAGE_SIZE } from "../../utils/constants";

export function useBookings() {
const queryClient = useQueryClient();
const [searchParams] = useSearchParams();

// FILTER
Expand All @@ -30,5 +33,21 @@ export function useBookings() {
queryFn: () => getBookings({ filter, sortBy, page }),
});

// PRE-FETCHING: PAGINATION
const pageCount = Math.ceil(count / PAGE_SIZE);

if (page < pageCount) {
queryClient.prefetchQuery({
queryKey: ["bookings", filter, sortBy, page + 1],
queryFn: () => getBookings({ filter, sortBy, page: page + 1 }),
});
}
if (page > 1) {
queryClient.prefetchQuery({
queryKey: ["bookings", filter, sortBy, page - 1],
queryFn: () => getBookings({ filter, sortBy, page: page - 1 }),
});
}

return { isLoading, error, bookings, count };
}
2 changes: 1 addition & 1 deletion src/utils/constants.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const PAGE_SIZE = 10;
export const PAGE_SIZE = 6;

0 comments on commit 3ae195e

Please sign in to comment.