javascript - 如何在 handleSubmit 中从 react-query 实现 useMutation

标签 javascript reactjs forms react-hooks react-query

我试图重写此提交函数以使用 react 查询 useMutation,但我收到错误。有人知道如何将其更改为使用 useMutation 编写吗?非常感谢您对这个问题的每一个提示和每一个答案。

async function handleSubmit(e) {
    e.preventDefault();
    try {
      if (file) {
        // if file is set send it to cloudinary api
        const url = `https://api.cloudinary.com/v1_1/${CLOUD_NAME}/upload`;
        loading(true);
        const formData = new FormData();
        formData.append("file", file);
        formData.append("upload_preset", UPLOAD_PRESET);

        const res = await fetch(url, {
          method: "POST",
          body: formData,
        });
        // get data and pull out 1000w image url
        const data = await res.json();
        const fileUrl = await data.eager[0].secure_url;
        console.log(fileUrl);
        setError("");
        if (album.trim() !== "" && color.trim() !== "" && fileUrl) {
          // Craeting Date form
          const albumData = new FormData();
          albumData.append("name", album);
          albumData.append("bckImgUrl", fileUrl);
          albumData.append("color", color);
          // change albumData to json
          const object = {};
          albumData.forEach((value, key) => (object[key] = value));
          // sending data to /api/v1/albums
          const res = await fetch(`${SERVER_API}/api/v1/albums`, {
            method: "POST",
            body: JSON.stringify(object),
            headers: {
              "Content-Type": "application/json",
            },
          });
          if (!res.ok) {
            const message = `An error has occured: ${res.status}`;
            setError(message);
          }
          const data = await res.json();
          const id = await data.data._id;
          loading(false);
          history.push(`/albums/${id}`);
        } else {
          setError("Please enter all the field values.");
        }
      } else {
        setError("Please select a file to add.");
      }
    } catch (error) {
      error.response && setError(error.response.data);
    }
  }

最佳答案

类似的东西。越简单越好

Codesandbox演示链接

import { Fragment, useState } from "react";
import axios from "axios";
import { useMutation } from "react-query"; 

const senRequest = async () => {
  return await axios.get("https://jsonplaceholder.typicode.com/posts");
};

export default function App() {
  const [val, setVal] = useState("");
  const [result, setResult] = useState([]);

  const { mutate } = useMutation(senRequest); // if you need to send data configure it from here
  const handleSubmit = (e) => {
    e.preventDefault();
    mutate(senRequest, { // And send it in here.
      onSuccess: ({ data }) => {
        setResult(data.slice(0, 5));
      }
    });
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input value={val} onChange={(e) => setVal(e.target.value)} />
        <button type="submit">Submit</button>
      </form>
      {result.map((el) => (
        <Fragment key={el.id}>
          <div
            style={{
              width: "100%",
              borderBottom: "1px solid gray"
            }}
          >
            <span>{el.title}</span>
            <span>{el.body}</span>
          </div>
        </Fragment>
      ))}
    </div>
  );
}

关于javascript - 如何在 handleSubmit 中从 react-query 实现 useMutation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65399600/

相关文章:

javascript - $emit 或 $broadcast 一个事件从 Controller 到指令 AngularJS

javascript - Reactjs - 渲染登录组件

javascript - react-redux 将 props 传递给子组件 props

forms - 在 VBA 中的帧之间拖放

当事件被另一个函数的元素调用时,Javascript 函数不起作用

javascript - 不正确的 JSHint 警告 "variable is defined but never used."

javascript - 在 ECMA-262 严格模式下是否允许 '\0' 后跟字符串中的十进制数字?

reactjs - React Native 样式中组件之间的空间

php - 以 symfony 形式添加链接

C# - move 时使表单半透明