Reputation: 181
query,
I'm making a bulletin board right now.
So, I put the values of title, content
in the Form
information into the react-query
function onSuccess
. In the value, console.log does not react.
export const useAddFAQPost = () => {
return useMutation(FaqPost)
}
export function FaqPost(data: FAQ) {
return axios.post<FAQ>('/add', data, {
})
}
const { mutate } = useAddFAQPost()
const onSubmit = useCallback((event: React.ChangeEvent<FormEvent>) => {
event.preventDefault();
return mutate({ title, type } as FAQ), {
onSuccess: async (data: string, context: string) => {
console.log(data);
console.log('why not?');
},
onError: async (data: string, context: string) => {
console.log(data);
}
};
}, [title, type])
return (
<>
<form onSubmit={onSubmit}>
<input type="text" name="title" value={title} ... />
<option value="faq">FAQ</option>
</form>
</>
)
If onSubmit succeeds or fails, the console.log in onSuccess, onError should be recorded, but it is not being recorded. Why are you doing this? onSuccess, onError doesn't seem to respond.
I don't know why. Help
Upvotes: 10
Views: 29095
Reputation: 41
You can also use mutateAsync, wait for the async to finish, and get the response if needed in a particular scenario.
Upvotes: 2
Reputation: 650
The accepted answer is incorrect. The onSuccess/onError handler is also available on the 'mutate' method (https://react-query.tanstack.com/reference/useMutation).
The catch here is that those additional callbacks won't run if your component unmounts before the mutation finishes. So, you have to make sure the component where you are doing the mutation does not unmount. In your case:
const {
mutate
} = useAddFAQPost()
const onSubmit = useCallback((event: React.ChangeEvent < FormEvent > ) => {
event.preventDefault();
return mutate({
title,
type
}
as FAQ), {
onSuccess: async(data: string, context: string) => {
console.log(data);
console.log('why not?');
},
onError: async(data: string, context: string) => {
console.log(data);
},
onSettled: () => {
// Some unmounting action.
// eg: if you have a form in a popup or modal,
// call your close modal method here.
// onSettled will trigger once the mutation is done either it
// succeeds or errors out.
}
};
}, [title, type])
Upvotes: 29
Reputation: 2520
The onSuccess / onError and so on method should be define in the useMutation hook creation and not when you call the mutate function as per documention.
https://react-query.tanstack.com/guides/mutations
You'll have to adapt to your need but the idea is:
export const useAddFAQPost = () => {
return useMutation(FaqPost, {
onSuccess: async (data: string, context: string) => {
console.log(data);
console.log('why not?');
},
onError: async (data: string, context: string) => {
console.log(data);
}
})
}
You could also pass it when you call useAddFAQPost()
Upvotes: -5