T
TanStack2w ago
national-gold

How to wait for `setQueryData` in `mutation.onSuccess`?

injectMutation({
mutationFn: () =>...
onSuccess: (res) => { this.queryClient.setQueryData(
MY_KEY,
(previous: Data | null) => return res );
}

console.log("empty", this.myKeyQuery.query.data())
injectMutation({
mutationFn: () =>...
onSuccess: (res) => { this.queryClient.setQueryData(
MY_KEY,
(previous: Data | null) => return res );
}

console.log("empty", this.myKeyQuery.query.data())
How to wait here until the query is updated? As the operation is not synchronous as it seems the query isn't populated at that point. Is there any way to make it synchronous or wait for the execution?
2 Replies
dependent-tan
dependent-tan2w ago
setQueryData is synchronous so there's nothing to await
national-gold
national-goldOP2w ago
That's odd because the data signal that has just been set is still empty. If I wrap it in setTimeout it's populated.
setTimeout(() => {
console.log("populated", this.myKeyQuery.query.data())
})
setTimeout(() => {
console.log("populated", this.myKeyQuery.query.data())
})
maybe it's a signal timing issue Just for reference.
principal = injectQuery(() => ({
queryKey: authKeys.all,
queryFn: () => {
return this.authApiService.fetchProfileAsync()
},
staleTime: ONE_HOUR,
enabled: !!this.stateService.get('token'),
}));

login = injectMutation(() => ({
mutationFn: async ({ email, password }: LoginDto) => {
return this.authApiService.loginAsync(email, password);
},
onSuccess: async (principalResponse) => {
this.queryClient.setQueryData(
authKeys.all,
(previous) => {
return principalResponse
});

console.log("undefined", this.principal.data());
setTimeout(() => {
console.log("defined", this.principal.data())
})
},
}));
principal = injectQuery(() => ({
queryKey: authKeys.all,
queryFn: () => {
return this.authApiService.fetchProfileAsync()
},
staleTime: ONE_HOUR,
enabled: !!this.stateService.get('token'),
}));

login = injectMutation(() => ({
mutationFn: async ({ email, password }: LoginDto) => {
return this.authApiService.loginAsync(email, password);
},
onSuccess: async (principalResponse) => {
this.queryClient.setQueryData(
authKeys.all,
(previous) => {
return principalResponse
});

console.log("undefined", this.principal.data());
setTimeout(() => {
console.log("defined", this.principal.data())
})
},
}));

Did you find this page helpful?