T
TanStack4y ago
exotic-emerald

Query selector returning old data

I have an API that returns the new record on create/update so I am using setQueryData inside the update mutation to update the cache instead of invalidating and refetching. In my app I show the list of records, with an option to hide some inactive records.
const showActiveOnlyFn = (records) => records.filter(r => r.active)
const {data} = useGetRecordsQuery(onlyShowActive ? { select: showActiveOnlyFn } : undefined)
const showActiveOnlyFn = (records) => records.filter(r => r.active)
const {data} = useGetRecordsQuery(onlyShowActive ? { select: showActiveOnlyFn } : undefined)
And here is the custom hook:
const useGetRecordsQuery = (options) => useQuery({queryKey: "records", queryFn: axiosFn, select: options?.select});
const useGetRecordsQuery = (options) => useQuery({queryKey: "records", queryFn: axiosFn, select: options?.select});
If I update the record to be inactive, it will dissapear when onlyShowActive is ticked. When I untick onlyShowActive the record appears again. But then when I update the record back to active, and tick onlyShowActive, the record is not shown, even though in react query devtools I can see that the record is correctly marked as active.
1 Reply
exotic-emerald
exotic-emeraldOP4y ago
Nevermind. I fixed it by adding
const showAllFn = (records) => records
const showAllFn = (records) => records
And changing the useGetRecordsQuery call to
useGetRecordsQuery({select: onlyShowActive ? showActiveOnlyFn : showAllFn})
useGetRecordsQuery({select: onlyShowActive ? showActiveOnlyFn : showAllFn})

Did you find this page helpful?