-
I am trying to write a code that fetches some data with a staleTime of 5 seconds. If the component mounts and finds data that are more than 5 seconds old, a refetch is triggered. I am able to achieve that without a problem with the following code : const { data: planets } = useQuery<Planet[]>(["starWars", "Planets"], {
queryFn: async () => {
const response = await fetch("https://swapi.dev/api/planets");
const d = await response.json();
return d.results;
},
staleTime: 5000
}) Then i created a mutation to optimistically add a planet const { mutate: addPlanetMutation } = useMutation(["starWars", "addPlanets"], {
mutationFn: (payload: Planet) => {
return Promise.resolve<Planet>(payload)
},
onMutate: (payload) => {
queryClient.setQueryData<Planet[]>(["starWars", "Planets"], (old) =>
[...(old ?? []), payload],
)
},
}) The problem here is that I was able to work around the problem by doing this when mutating : onMutate: (payload) => {
const queryClientCache = queryClient.getQueryCache();
const planetsCache = queryClientCache .find(["starWars","Planets"]);
queryClient.setQueryData<Planet[]>(["starWars", "Planets"], (old) =>
[...(old ?? []), payload], {
updatedAt: planetsCache?.state.dataUpdatedAt
}
)
}, By accessing the timestamp at which the last refetch was ran, i am able to achieve what i want, but is there a better way ? PS : I found this while working on a POC for my company, the code can be found here : https://github.com/Pumkko/PocReactQueryForKim |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Two ways to address this:
|
Beta Was this translation helpful? Give feedback.
Two ways to address this:
as you've said, you can pass
updatedAt
as options tosetQueryData
. It defaults toDate.now()
because we assume that data that you write to the cache is from "now" at the time of writing. UsingdataUpdatedAt
from what is currently in the cache seems good.Usually, with optimistic updates, you'd just
invalidate
inonSettled
. That makes sure that no matter what, at the end of your mutation, your entry is refetched from the server if it is currently used or marked as stale if it's unused so that it will be refetched when you mount it the next time.