简体   繁体   English

如何在我的组件中使用 react/tanstack 查询 useMutation

[英]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.

相关问题 我想从组件外部运行 tanstack react 查询,因为我不能在那里使用 useQuery? - I want to run tanstack react query from outside of the component since I cannot use useQuery there? react-query中如何使用useMutation的响应来显示数据? - How to use the response of useMutation in react-query to display data? React Query useMutation 将我的 API 调用 state 置于空闲状态 - React Query useMutation is putting my API call state in Idle 带有可重用 function 抛出错误的 Tanstack/React 查询 - Tanstack/React query with a reusable function throwing errors 如何在handleSubmit中从react-query实现useMutation - How to implemet useMutation from react-query in handleSubmit 反应查询 useMutation onError 从不触发 - react-query useMutation onError never firing 反应查询:反应性 useMutation 结果 - react-query: reactive useMutation results 如何解决 TypeError:使用 useMutation react hook 时无法读取 react js 中未定义的属性“then” - How to solve TypeError: Cannot read property 'then' of undefined in react js when in use of useMutation react hook 如何在 React native 中实现 UseMutation? - How to implement UseMutation inside React native? 反应查询 useMutation + axios 帖子保持返回数据为“未定义” - React query useMutation + axios post keeps returning data as "undefined"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM