Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`react-query` mutate onSuccess function not responding

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

like image 353
minsu Avatar asked Mar 22 '26 08:03

minsu


1 Answers

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])
like image 77
rivnatmalsa Avatar answered Mar 24 '26 22:03

rivnatmalsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!