T
TanStack•4y ago
flat-fuchsia

useMutation onError behavior

Hey there, I'm freaking out here. I'm sending a POST using useMutation , and if the API returns any errors I call setErrors inside onError callback. But I don't understand why setErrors is only being updated when I click in the Submit Button for the 2nd time.
const { mutate: createPost, isLoading: isLoadingCreatePost } = useCreatePost({
onSuccess: (data) => {
console.log(data);
},
onError: (error) => {
setErrors(error?.response?.data.errors);
console.log(errors);
},
});
const { mutate: createPost, isLoading: isLoadingCreatePost } = useCreatePost({
onSuccess: (data) => {
console.log(data);
},
onError: (error) => {
setErrors(error?.response?.data.errors);
console.log(errors);
},
});
const handleCreatePost = () => {
useCreatePost({
accountId,
name,
members: members.map((member) => member.id),
});
};
const handleCreatePost = () => {
useCreatePost({
accountId,
name,
members: members.map((member) => member.id),
});
};
Hook:
export const useCreatePost = (
config: UseMutationOptions<
void,
AxiosError,
{ accountId; name; members }
> = {}
) => {
return useMutation(
(payload): Promise<void> =>
api.post(`account/${payload.accountId}/crew`, payload),
{
...config,
}
);
};
export const useCreatePost = (
config: UseMutationOptions<
void,
AxiosError,
{ accountId; name; members }
> = {}
) => {
return useMutation(
(payload): Promise<void> =>
api.post(`account/${payload.accountId}/crew`, payload),
{
...config,
}
);
};
3 Replies
flat-fuchsia
flat-fuchsiaOP•4y ago
Or, shouldn't I add errors in state and use it from react-query? :sus: I'm still diving into abstract the states in my mind.
eastern-cyan
eastern-cyan•4y ago
why do you need to call setErrors ? useMutation returns the errors directly, next to the isLoading state and the mutate function ... also, what's this?
const handleCreatePost = () => {
useCreatePost({
const handleCreatePost = () => {
useCreatePost({
this violates the rules of hooks? 🙃
flat-fuchsia
flat-fuchsiaOP•4y ago
yes, I notice that right now, I actually call the mutate there, but I wrote the hook by accident. I'm suffering from terminal stupidity :eheh:

Did you find this page helpful?