How to use cache value immediately after mutation? #9273
-
Hello all (and if you are maintainer, thank you!). I have a question about using cache values immediately after I want to do something like this with mutations: const { refetch } = useSomeQuery(id);
const queryClient = useQueryClient();
const fetchAndDoSomething = async () => {
const response = await refetch();
doSomethingWith(response.data);
} where I would like to do the same thing with mutations, but I'm not sure how to return anything from a mutation function. So I do something like this: const { mutate } = useMutation(someMutationThatUpdatesQueryCacheOnSettled);
const queryClient = useQueryClient();
const fetchAndDoSomething = async () => {
const response = await mutate();
const data = queryClient.getQueryData(MyQueryKey)
doSomethingWith(data);
} I notice that when I write with this pattern (mutate + set query cache data, and then try to get the runtime value of the The only ways I have gotten this to work have been to:
const { mutate } = useMutation(someMutation);
const queryClient = useQueryClient();
const fetchAndDoSomething = async () => {
await mutate();
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
if (event.query.queryKey.toString() === queryKey.toString() && event.type === 'updated') {
unsubscribe();
if (event.query.state.status === 'success') {
doSomethingWith(event.query.state.data);
}
}
});
}
const [doSomething, setDoSomething] = useState(false);
const { mutate } = useMutation(someMutation);
const { data } = useQuery(QueryKeyMutationUpdates);
const queryClient = useQueryClient();
const fetchAndDoSomething = async () => {
await mutate();
setDoSomething(true);
}
useEffect(() => {
if (!data || !doSomething) return;
doSomethingWithData(data);
setDoSomething(false);
}, [data, doSomething]);
Maybe I'm missing something (something as simple as returning a value from Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Edit: Prev answer: (I am a little concerned about stale closures and whether you need to pass the mutation function into the mutation key array, but the function I'm writing "lives" outside of React so doesn't rely on state variables—hence the desire to get runtime values) |
Beta Was this translation helpful? Give feedback.
Edit:
Use
mutateAsync
.Prev answer:
I'm silly. You can pass a callback function to the wrapper function.
(I am a little concerned about stale closures and whether you need to pass the mutation function into the mutation key array, but the function I'm writing "lives" outside of React so doesn't rely on state variables—hence the desire to get runtime values)