`react-query` 改变 onSuccess 函数没有响应

`react-query` mutate onSuccess function not responding

查询, 我现在正在做一个公告板。 于是,我把Form信息中title, content的值放到了react-query函数中onSuccess。在值中,console.log没有反应。

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>
 </>
)

如果onSubmit成功或者失败,onSuccess,onError中的console.log应该被记录,但是没有被记录。你为什么做这个? onSuccess, onError好像没反应

我不知道为什么。帮助

onSuccess / onError 等方法应该在 useMutation 挂钩创建中定义,而不是在您根据文档调用 mutate 函数时定义。

https://react-query.tanstack.com/guides/mutations

你必须适应你的需要,但想法是:

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);
       } 
    })
}

也可以在调用时传递useAddFAQPost()

接受的答案不正确。 onSuccess/onError 处理程序也可用于 'mutate' 方法 (https://react-query.tanstack.com/reference/useMutation)。

这里要注意的是,如果您的组件在变更完成之前卸载,那么这些额外的回调将不会 运行。因此,您必须确保您正在执行更改的组件不会卸载。你的情况:

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 its succeeds or errors out.
            }
        };
    }, [title, type])