[英]How to use react/tanstack query useMutation in my component
I'm currently converting the logic in my mern (with typescript) project to use React/Tanstack query to learn this tool better.我目前正在将我的 mern(使用 typescript)项目中的逻辑转换为使用 React/Tanstack 查询来更好地学习这个工具。
I want to use useMutation to handle the post request logic from the details inputted in the form, in this login component but can't figure out how to do this.我想使用 useMutation 来处理表单中输入的详细信息的发布请求逻辑,在此登录组件中,但无法弄清楚如何执行此操作。 Any tips would be appreciated thanks.
任何提示将不胜感激。 Below is the code from my login component
下面是我的登录组件的代码
const Login = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const [state, setState] = useContext(UserContext);
const handleSubmit = async (e: { preventDefault: () => void }) => {
e.preventDefault();
let response;
const { data: loginData } = await axios.post("http://localhost:5001/auth/login", {
email,
password,
});
response = loginData;
if (response.errors.length) {
return setErrorMsg(response.errors[0].msg);
}
setState({
data: {
id: response.data.user.id,
email: response.data.user.email,
stripeCustomerId: response.data.user.stripeCustomerId,
},
loading: false,
error: null,
});
localStorage.setItem("token", response.data.token);
axios.defaults.headers.common["authorization"] = `Bearer ${response.data.token}`;
navigate("/dashboard");
};
return (
<div className="login-card">
<div>
<h3>Login</h3>
</div>
<form onSubmit={handleSubmit}>
<div className="login-card-mb">
<label>Email</label>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="login-card-mb">
<label>Password</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
{errorMsg && <p>{errorMsg}</p>}
<button type="submit">Submit</button>
</form>
</div>
);
};
After setting up your project to use React Query ( Check the docs if you have not).在设置项目以使用 React Query 之后(如果没有,请查看文档)。 You want to extract your api call to a separate function that takes an object. This object will hold the values you would like to post.
您想要将您的 api 调用提取到一个单独的 function,它需要一个 object。这个 object 将保存您想要发布的值。
const Login = (dataToPost) => {
let res = await axios.post('url', dataToPost)
return res.data
}
Now that you have that, you can import useMutation
from React Query.现在您已经有了,您可以从 React Query 导入
useMutation
。 Once imported you can now use the hook.导入后,您现在可以使用挂钩。 UseQuery, useMutation both contain a data variable so no need to create state for the data returned from your endpoint.
UseQuery、useMutation 都包含一个数据变量,因此无需为从端点返回的数据创建 state。 In this example, I'm deconstructing the data and loading state. But most importantly the mutate function. Which allows you to fire off your api call.
在此示例中,我正在解构数据并加载 state。但最重要的是变异 function。它允许您触发 api 调用。 We add our api call to the hook.
我们将 api 调用添加到挂钩中。 I'm renaming the mutate function to
doLogin
.我将 mutate function 重命名为
doLogin
。 It's a habit这是一种习惯
const {data,isLoading,mutate:doLogin} = useMutation(Login)
Finally we can just call mutate(objectWithValues)
wherever you want in your code.最后,我们可以在代码中的任意位置调用
mutate(objectWithValues)
。 The data
will initially be null and isLoading
will be true once called. data
最初为 null,调用后isLoading
将为真。 To tie it all together.把它们绑在一起。 Your handleSubmit could look as follows
您的 handleSubmit 可能如下所示
const handleSubmit = () => {
e.preventDefault();
doLogin({email,password})
}
You also have the option of running functions on a success or error of the mutation您还可以选择在突变成功或错误时运行函数
const {data,isLoading,mutate: doLogin} =
useMutation(Login, {
onError: (err) => console.log("The error",err),
onSuccess:(someStuff)=>console.log("The data being returned",someStuff)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.