GraphQl- reactj添加数据
#javascript #网络开发人员 #react #graphql

大家好,在GraphQl系列的这一部分中,我们将使用Apollo客户端软件包获取数据。

在我们在previosu部分创建的“ queries.ts”文件中,在底部添加此代码。

export const CREATE_USER = gql`
  mutation CreateUser($newUser: CreateUser!) {
    createUser(newUser: $newUser) {
      role
      name
      isEmployee
      age
    }
  }
`;

export const UPDATE_USER = gql`
  mutation UpdateUser($updatedUser: UpdateUser!) {
    updateUser(updatedUser: $updatedUser) {
      id
      name
      role
      age
      isEmployee
    }
  }
`;

因此,我们创建了一个查询,以添加具有角色,名称,Isemployee和年龄字段的用户,并且用于更新用户

进口

import { useMutation } from "@apollo/client";
import { CREATE_USER, UPDATE_USER, ALL_USERS } from "./Queries";
import { useCounterStore } from "./UsersList";
  • 我们已经导入USEMOUNT挂钩,以将方法与OnClick和OnSubmit事件处理程序一起使用
  • create_user,update_user和all_user是我们的查询
  • USECOUNTERSTORE来自我们的用户列表组件以访问状态及其setter函数

访问状态和设定器功能

...
const CreateUser = () => {

  const id = useCounterStore((state) => state.id);
  const name = useCounterStore((state) => state.name);
  const setName = useCounterStore((state) => state.setName);
  const age = useCounterStore((state) => state.age);
  const setAge = useCounterStore((state) => state.setAge);
  const role = useCounterStore((state) => state.role);
  const setRole = useCounterStore((state) => state.setRole);
  const isEmployee = useCounterStore((state) => state.isEmployee);
  const setIsEmployee = useCounterStore((state) => state.setIsEmployee);
  const isUpdate = useCounterStore((state) => state.isUpdate);
  const setIsUpdate = useCounterStore((state) => state.setIsUpdate);

...

输入字段处理程序方法

...

const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAge(Number(event.target.value));
  };

  const handleOptionChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ): void => {
    setIsEmployee(event.target.value === "true");
  };

  const handleRoleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setRole(event.target.value);
  };

...
  • 为每个输入创建处理程序方法

为添加和更新用户创建方法

...

 const [createUser] = useMutation(CREATE_USER, {
    refetchQueries: [{ query: ALL_USERS }],
  });

  const [updateUser] = useMutation(UPDATE_USER, {
    refetchQueries: [{ query: ALL_USERS }],
  });

...
  • createuser和updateuser是我们的方法,我们可以将其附加到活动侦听器中,内部有2个参数,第一个是查询本身,第二个是refetch方法,因此,每当我们添加或更新用户时,All_user,查询将与之一起运行,并实时显示最新数据。

表单输入

...

return (
    <form className="flex flex-wrap items-center justify-center gap-5 py-5 px-4 bg-gradient-to-r from-slate-800 to-black">
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Name</label>
        <input
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl"
          type="text"
          value={name}
          onChange={handleNameChange}
        />
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Age</label>
        <input
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl"
          type="number"
          value={age}
          onChange={handleAgeChange}
        />
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Role</label>
        <select value={role}
          onChange={handleRoleChange}
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl">
            <option> WebDeveloper</option>
            <option>Tester</option>
            <option>SoftwareEngineer</option>
        </select>
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <p className="font-semibold text-white">Employee</p>
        <label className="text-white">
          <input
            type="radio"
            value="true"
            checked={isEmployee === true}
            onChange={handleOptionChange}
          />
          True
        </label>

        <label className="text-white">
          <input
            type="radio"
            value="false"
            checked={isEmployee === false}
            onChange={handleOptionChange}
          />
          False
        </label>
      </div>

...
  • 我们为名称和年龄创建了2个输入FIEL,请选择“员工状态”的角色和无线电输入。

添加或更新的按钮条件

...

   <div className="flex justify-center w-full md:w-fit ml-4 md:ml-0">
        {isUpdate ? (
          <>
            <button
              className="px-4 py-2 rounded-lg bg-blue-400 text-white"
              onClick={(e) => {
                e.preventDefault();
                if (name === "" || role === "") {
                  alert("Fill all the details");
                } else {
                  updateUser({
                    variables: {
                      updatedUser: {
                        id,
                        name,
                        age,
                        role,
                        isEmployee,
                      },
                    },
                  }).then(() => {
                    setName("");
                    setAge(18);
                    setRole("");
                    setIsEmployee(false);
                  });

                  setIsUpdate(false);
                }
              }}
            >
              Update
            </button>

            <button
              className="px-4 py-2 rounded-lg bg-red-400 text-white ml-3"
              onClick={() => {
                setIsUpdate(false);
                setName("");
                setAge(18);
                setRole("");
                setIsEmployee(false);
              }}
            >
              Cancel
            </button>
          </>
        ) : (
          <button
            className="px-4 py-2 rounded-lg bg-blue-600 text-white"
            onClick={(e) => {
              e.preventDefault();
              if (name === "" || role === "") {
                alert("Fill all the details");
              } else {
                createUser({
                  variables: {
                    newUser: {
                      name,
                      age,
                      role,
                      isEmployee,
                    },
                  },
                }).then(() => {
                  setName("");
                  setAge(18);
                  setRole("");
                  setIsEmployee(false);
                });
              }
            }}
          >
            Add
          </button>
        )}
      </div>
...
  • 我们正在检查一个isupdate态,如果是true,请使用UpdateUser方法显示更新按钮,如果它是false,请使用CreateUser方法显示添加按钮。在Create或Update用户的两个方法中,我们都有变量对象,并且在其中,我们的对象具有与查询参数名称相同的对象,该名称是CreateUser和“ UpdateUser”的“ Newuser”,我们将从显示组件中控制此状态,我们将在本系列的下一部分中进行讨论。

完成代码

import { useMutation } from "@apollo/client";
import { CREATE_USER, UPDATE_USER, ALL_USERS } from "./Queries";
import { useCounterStore } from "./UsersList";

const CreateUser = () => {

  const id = useCounterStore((state) => state.id);
  const name = useCounterStore((state) => state.name);
  const setName = useCounterStore((state) => state.setName);
  const age = useCounterStore((state) => state.age);
  const setAge = useCounterStore((state) => state.setAge);
  const role = useCounterStore((state) => state.role);
  const setRole = useCounterStore((state) => state.setRole);
  const isEmployee = useCounterStore((state) => state.isEmployee);
  const setIsEmployee = useCounterStore((state) => state.setIsEmployee);
  const isUpdate = useCounterStore((state) => state.isUpdate);
  const setIsUpdate = useCounterStore((state) => state.setIsUpdate);

  const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAge(Number(event.target.value));
  };

  const handleOptionChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ): void => {
    setIsEmployee(event.target.value === "true");
  };

  const handleRoleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setRole(event.target.value);
  };

  const [createUser] = useMutation(CREATE_USER, {
    refetchQueries: [{ query: ALL_USERS }],
  });

  const [updateUser] = useMutation(UPDATE_USER, {
    refetchQueries: [{ query: ALL_USERS }],
  });

  return (
    <form className="flex flex-wrap items-center justify-center gap-5 py-5 px-4 bg-gradient-to-r from-slate-800 to-black">
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Name</label>
        <input
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl"
          type="text"
          value={name}
          onChange={handleNameChange}
        />
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Age</label>
        <input
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl"
          type="number"
          value={age}
          onChange={handleAgeChange}
        />
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <label className="font-semibold text-white">Role</label>
        <select value={role}
          onChange={handleRoleChange}
          className="border border-blue-400 px-2 py-1 w-52 rounded-2xl">
            <option> WebDeveloper</option>
            <option>Tester</option>
            <option>SoftwareEngineer</option>
        </select>
      </div>
      <div className="flex gap-4 justify-between w-full md:w-fit items-center">
        <p className="font-semibold text-white">Employee</p>
        <label className="text-white">
          <input
            type="radio"
            value="true"
            checked={isEmployee === true}
            onChange={handleOptionChange}
          />
          True
        </label>

        <label className="text-white">
          <input
            type="radio"
            value="false"
            checked={isEmployee === false}
            onChange={handleOptionChange}
          />
          False
        </label>
      </div>
      <div className="flex justify-center w-full md:w-fit ml-4 md:ml-0">
        {isUpdate ? (
          <>
            <button
              className="px-4 py-2 rounded-lg bg-blue-400 text-white"
              onClick={(e) => {
                e.preventDefault();
                if (name === "" || role === "") {
                  alert("Fill all the details");
                } else {
                  updateUser({
                    variables: {
                      updatedUser: {
                        id,
                        name,
                        age,
                        role,
                        isEmployee,
                      },
                    },
                  }).then(() => {
                    setName("");
                    setAge(18);
                    setRole("");
                    setIsEmployee(false);
                  });

                  setIsUpdate(false);
                }
              }}
            >
              Update
            </button>

            <button
              className="px-4 py-2 rounded-lg bg-red-400 text-white ml-3"
              onClick={() => {
                setIsUpdate(false);
                setName("");
                setAge(18);
                setRole("");
                setIsEmployee(false);
              }}
            >
              Cancel
            </button>
          </>
        ) : (
          <button
            className="px-4 py-2 rounded-lg bg-blue-600 text-white"
            onClick={(e) => {
              e.preventDefault();
              if (name === "" || role === "") {
                alert("Fill all the details");
              } else {
                createUser({
                  variables: {
                    newUser: {
                      name,
                      age,
                      role,
                      isEmployee,
                    },
                  },
                }).then(() => {
                  setName("");
                  setAge(18);
                  setRole("");
                  setIsEmployee(false);
                });
              }
            }}
          >
            Add
          </button>
        )}
      </div>
    </form>
  );
};

export default CreateUser;

在此GraphQl系列的下一部分中,我们将使用“ USEMOUNT”挂钩介绍数据的更新和删除功能。
感谢您检查此帖子
您可以与我联系 -
Instagram -https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
电子邮件-shubhmtiwri00@gmail.com

^^您可以在下面的链接上为我提供一些捐款,谢谢^^^
1o111⁄-> https://www.buymeacoffee.com/waaduheck < -

也检查这些帖子
https://dev.to/shubhamtiwari909/website-components-you-should-know-25nm

https://dev.to/shubhamtiwari909/smooth-scrolling-with-js-n56

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/custom-tabs-with-sass-and-javascript-4dej