0

I have page that displays data using react infinite scroll. Every time I get to the last item, it fetches new data and add it to the UI.

I also want to add search bar. In the search bar the user can search for specific data. After he typed what he looking for, there needs to be an api call and fetch the data (filtered data) from database.

How can I combine these two effects.

So far, I have created the infinite scroll using react-query. Now I also want to achieve the search bar effect.

Infinite scroll code

const [query, setQuery] = useState<string>("");
const { ref, inView } = useInView();
  const { data, status, error, hasNextPage, fetchNextPage } = useInfiniteQuery({
    queryKey: ["coupons"],
    queryFn: getPaginatedCoupons,
    initialPageParam: 1,
    staleTime: Infinity,
    refetchOnWindowFocus: false,
    getNextPageParam: (lastPage, allPages) => {
      const nextPage = lastPage?.length ? allPages.length + 1 : undefined;
      return nextPage;
    },
  });

useEffect(() => {
    if (inView && hasNextPage) {
      fetchNextPage();
    }
  }, [inView, hasNextPage, fetchNextPage]);


return (
    <div className="flex flex-col items-center justify-center mt-10">
      <div className="flex w-3/4 items-center justify-center">
        <SearchBar filter={handleCouponsFilter} />
      </div>
      <div className="grid grid-rows-1 md:grid-cols-12 lg:grid-cols-12 p-0 md:p-0 lg:p-0 justify-center items-center mt-11 justify-items-center">
        {coupons &&
          coupons.map((coupon, index) => {
            if (index === coupons.length - 1) {
              return (
                <div
                  key={index}
                  className="flex justify-center col-span-12 sm:col-span-12 md:col-span-4 w-full"
                >
                  {coupon && (
                    <CouponCard innerRef={ref} card={coupon} key={index} />
                  )}{" "}
                </div>
              );
            } else {
              return (
                <div
                  key={index}
                  className="flex justify-center col-span-12 sm:col-span-12 md:col-span-4 w-full"
                >
                  {coupon && <CouponCard card={coupon} key={index} />}{" "}
                </div>
              );
            }
          })}
      </div>
    </div>
  );
};

This is the infinite scroll and it works fine. But how do I add the functionality of the search bar to the infinite scroll?

1 Answer 1

1

For that just make the following changes:

  1. Include your search param in queryKey: queryKey: ["coupons", query]

  2. Handle the search value in your getPaginatedCoupons method. You will have to pass the new search value in that method and make the API call accordingly.

Here is one basic implementation:

useInfiniteQuery({
    queryKey: ["projects", query],
    queryFn: async ({ pageParam }) => {
        const res = await axios.get("/api/countries", {
        params: {
            cursor: pageParam,
            namePrefix: query,
        },
        });
        return res.data;
    },
    initialPageParam: 0,
    getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined,
    getNextPageParam: (lastPage) => lastPage.nextId ?? undefined,
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.