T
TanStack2y ago
adverse-sapphire

Can manage to understand optimistic update.

Hello there, I'm trying to implement optimistic update in my application but I struggle a bit. Here is my function :
const addCardToCollection = ({
card,
collectionId,
userId,
}: {
card: Database['public']['Tables']['cards']['Row']
collectionId: Database['public']['Tables']['collections']['Row']['id']
userId: string
}) => {
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: async () => {
const res = await cardToCollection({
cardId: card.id,
collectionId,
userId,
})
// ---^ Return an object with count/data/error/status/statusText properties

return res
},
onMutate: async data => {
await queryClient.cancelQueries(['view_collection'])

console.log(data)
// ----------^ Return undefined
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['view_collection'] })
},
})

return {
mutate,
}
}
const addCardToCollection = ({
card,
collectionId,
userId,
}: {
card: Database['public']['Tables']['cards']['Row']
collectionId: Database['public']['Tables']['collections']['Row']['id']
userId: string
}) => {
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: async () => {
const res = await cardToCollection({
cardId: card.id,
collectionId,
userId,
})
// ---^ Return an object with count/data/error/status/statusText properties

return res
},
onMutate: async data => {
await queryClient.cancelQueries(['view_collection'])

console.log(data)
// ----------^ Return undefined
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['view_collection'] })
},
})

return {
mutate,
}
}
Few questions: - Do we agree than the onMutate function will be called before the mutationFn ? - Where are the data parameter on the onMutate function comes from ?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?