neoneyN
tRPC11mo ago
5 replies
neoney

state change not triggering refetch

I have this query in my app:

const [filter, setFilter] = useState({
    value: "",
    property: "coupon",
  });

  const [sorting, setSorting] = useState([
    {
      id: "createdAt",
      desc: false,
    },
  ]);

  const trpc = useTRPC();
  const queryCoupons = useInfiniteQuery(
    trpc.coupons.list.infiniteQueryOptions(
      {
        limit: pageSize,
        filter,
        direction: sorting[0]?.desc ? "backward" : "forward",
      },
      {
        getNextPageParam: (lastPage) => lastPage.nextCursor,
        getPreviousPageParam: (_firstPage, allPages) => {
          const firstPageCursor = allPages[0]?.result[0]?.createdAt;
          return firstPageCursor;
        },
      },
    ),
  );

When I change the filter parameter, the query refetches as usual.
However, when I change sorting[0].desc, it just doesn't. I've also tried to manually refetch it in a useEffect, but it just fetches with the stale input.
I tried refactoring the direction logic into a useMemo that just returns the string - that does nothing.
Again, I can confirm with a useEffect that the sorting direction does indeed change. It's also kinda weird that it works for filter and not direction.
Was this page helpful?