[英]mutateAsync data is undefined in submit event (react query)
I am currently trying to make a request to my API using React Query.我目前正在尝试使用 React Query 向我的 API 发出请求。 When I log my data inside the component function scope it logs fine and gives the data I expect, it also logs the correct data before the
handleSubmit
does.当我在组件 function scope 中记录我的数据时,它记录良好并给出了我期望的数据,它还在
handleSubmit
之前记录了正确的数据。 When I log my data variable inside handleSubmit
, after submitting, it always logs undefined.当我在
handleSubmit
中记录我的数据变量时,提交后,它总是记录未定义。
// useSignup.ts
import axios from "axios";
import { useMutation } from "react-query";
const signup = (credidentials: any) => {
return axios.post("/api/signup", credidentials);
};
const useSignup = () => {
return useMutation(signup);
};
export default useSignup;
// Signup.tsx
const {
mutateAsync: makeApiRequest,
isLoading,
isSuccess,
isError,
data: authData,
} = useSignup();
console.log(authData); // Updates fine and gives the correct data
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
await makeApiRequest(input);
console.log(authData); // Always undefined
};
because awaiting
makeApiRequest
does not, in the same event handler, make data from the hook "defined" right after that.因为在同一个事件处理程序中
awaiting
makeApiRequest
并不会在此之后立即从钩子“定义”中生成数据。 It's similar to:它类似于:
const [count, setCount] = React.useState(undefined)
<button onClick={() => {
setCount(1)
console.log(count)
}) />
here, logging the count will also be undefined
, as it will only be set to 1
in the next render cycle.在这里,记录计数也将是
undefined
,因为它只会在下一个渲染周期中设置为1
。 being async
doesn't change that - this is just how react works. async
不会改变这一点——这就是 react 的工作原理。
if you want to access data after a successful submit, use the onSuccess
callback of the mutate
function:如果要在提交成功后访问数据,请使用
mutate
function 的onSuccess
回调:
makeApiRequest(input, { onSuccess: newData => console.log(newData) }
you can also use mutateAsync
, which returns data from the mutation, but you need to catch errors manually and I don't think this is needed often.您也可以使用
mutateAsync
,它从突变中返回数据,但是您需要手动捕获错误,我认为这并不经常需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.