Waiting for invalidated query to be refreshed before navigating
Hello all:
I have a page where the user creates a new item in the database. I am invalidating the query that has the list of these items.
I would like to wait for the invalidated query to be reloaded before navigating back to the list so the user doesn't see it pop in after the fact.
I'm not sure how to watch for this to happen. I've got the following set up:
const isFetchingPosts = useIsFetching({ queryKey: ['myQueryName'] })
Then after the mutate happens I have tried using vueUse functions to watch the "count" of queries running and navigate when it is 0
if (isSuccess) {
invoke(async () => {
await until(isFetchingPosts).toMatch(v => v === 0)
await navigateTo('myPath')
})
}
I'm sure there is a more elegant way. I'm still a fairly new developer (even though I'm old!) so I would appreciate any ideas folks have.
Thanks very much!
Sam
3 Replies
ratty-blush•16mo ago
Are you invalidating inside mutation's onSuccess callback? If so you can add await to your queryClient.invalidateQueries call in there. This will make mutation stay in pending state until refetches have finished.
Then you can use await mutateAsync and only after that you navigate
wise-whiteOP•16mo ago
Hello @wlnt, thanks so much for your help!
I think I'm close but I'm still seeing the new item pop into my list after I've navigated back from creating a new item. Here is the page where I create the item:
const { isSuccess, mutateAsync } = await useCreateCoursePlan()
const formHandler = async formData => {
await mutateAsync(formData)
if (isSuccess) {
await navigateTo('/mypage')
} else {
console.log('Creation Failed')
}
}
And here is the composable returning the useMutation function:
export default async function () {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (formData: CoursePlansInsert) => {
await $fetch(
/api/v1/courseplans
, {
method: 'POST',
body: JSON.stringify(formData),
})
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['coursePlansList'] })
},
})
}
Thanks for any further insights you may have.
Samratty-blush•16mo ago
@Samsterism generally speaking this should work correctly, you may have made a mistake somewhere else. i can only say that
useCreateCoursePlan
composable itself doesn't have to be async but this is probably unrelated.