Mutating reactive query keys #52
Replies: 1 comment 7 replies
-
Hi, I do not see why you would need reactivity in this example. As for your example, I would go with: export const useUpdatePost = () => {
return useMutation((body) => axios.put(`/api/posts/${body.postId}`, {...body}),
{
onMutate: async (variables) => {
const queryKey = ['posts', { postId: variables.postId }];
await queryClient.cancelQueries(queryKey);
const previousData = queryClient.getQueryData(queryKey);
// Optimistically update to the new value
if (previousData) {
queryClient.setQueryData(queryKey, {
// updated data
});
}
return {
previousData,
};
},
onError: (_error, variables, context: any) => {
if (context?.previousData) {
queryClient.setQueryData(
['posts', { postId: variables.postId }],
context.previousData
);
}
},
onSettled: (_data, _error, variables, _context) => {
queryClient.invalidateQueries(['posts', { postId: variables.postId }]);
},
}
);
}; and call it like this: const postId = ref(1) // or computed
const updatePost = useUpdatePost()
onClick() {
updatePost.mutate({postId: postId.value, ...})
} Also if you are using it with a combination with const postId = ref(1) // or computed
const query = useQuery(reactive(['posts', { postId }]), fetchFn) I did not test the above, so in case it does not work, let me know. I will try to prepare some codesandbox example. |
Beta Was this translation helpful? Give feedback.
-
Say you have this
useQuery
composable:as you can see, the
postId
argument is aComputedRef
so that the query is reactive too.And to mutate a post, you also have to pass a
ComputedRef
instead of just thepostId
:Am I doing this correct? Do we need to wrap it again in a
ComputedRef/Ref
so that the query key is the same? Thanks!Beta Was this translation helpful? Give feedback.
All reactions