neoney
neoney2w ago

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;
},
},
),
);
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.
4 Replies
neoney
neoneyOP2w ago
seems like direction is special for useInfiniteQuery
Nick
Nick2w ago
Check you’re not mutating that variable, if the reference stays stable it may not trigger a refetch
neoney
neoneyOP2w ago
I was doing const direction = useMemo(() => sorting[0]?.desc ? "backward" : "forward", [sorting]) and it didn't work
Nick
Nick2w ago
But what about the setter for that state?

Did you find this page helpful?