-
The keepPreviousData option often comes up when talking about paginated queries (and filters in general). Indeed it is a great way to avoid hard loading states and makes the experience of adjusting filters better. But often query keys include values other than simple filters that completely changes the data. Think of a project id vs a search term that filters the project tasks. When the former changes, I expect a hard loading view, when the latter change I expect the data to stay with an indication of an ongoing refetching. Exampleconst useProject = (id: number, params : { page: number }) =>
useQuery({
queryKeys: [“project”, id, params],
queryFn: () => getProject(id, params),
keepPreviousData: true
}) When using this query, changing the project all together (i.e the id changed) keeps the previous data. In some contexts this would be very unexpected behavior. Even if you provide indication of the data being “previous”, it does not make sense for example to enter a user profile and see in the background another profile that you watched before. SuggestionThe keepPreviousData option could also be a function that returns a boolean. I propose this signature: keepPreviousData?:
| boolean
| ((
previousQuery: Query<…>,
currentQuery: Query<…>
) => boolean) Example usage: const useProject = (id: number, params : { page: number }) =>
useQuery({
queryKeys: [“project”, id, params],
queryFn: () => getProject(id, params),
keepPreviousData: (previousQuery, currentQuery) => previousQuery.queryKey[1] === currentQuery.queryKey[1]
}) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
in v5,
it doesn't have access to the |
Beta Was this translation helpful? Give feedback.
in v5,
keepPreviousData
has been merged withplaceholderData
, mainly because you can't have both placeholderData and previousData at the same time. So I think in v5, you can achieve this with:it doesn't have access to the
currentQuery
, but you can get access to thequeryKey
via closures.