Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
4
Indexable
Never
const AddNewCategory = ({ ...props }) => {
  const [name, setName] = useState(null);
  const [nonveg, setNonveg] = useState(false);
  const [mutateFunction, { data, loading, error }] = useMutation(
    ADD_NEW_CATEGORY,
    {
      variables: {
        name: name,
        nonveg: nonveg,
      },
    }
  );
  useEffect(() => {
    if (data) {
      toast.success("Category added successfully");
    }
  }, [data, error, loading]);
  const schema2 = z.object({
    name: z
      .string({
        required_error: "Name is required",
        invalid_type_error: "Name must be a string",
      })
      .min(2, { message: "Name must be at least 2 characters long" }),
    nonveg: z.string(),
  });
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ resolver: zodResolver(schema2) });

  const onSubmit = (data) => {
    setNonveg(data.nonveg === "true" ? true : false);
    setName(data.name);
    console.log("nonveg", nonveg, "name", name);
    mutateFunction();
    console.log(data);
  };
  return (
    <Grid>
      <Grid.Col span={4}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Title order={3}>Add New Category</Title>
          <TextInput
            value={name}
            onChange={(event) => setName(event.target.value)}
            label="Name"
            {...register("name")}
            error={errors.name?.message}
          />
          <Select
            error={errors.nonveg?.message}
            label="nonveg"
            placeholder="Nonveg?"
            value={nonveg}
            {...register("nonveg")}
            onChange={setNonveg}
            defaultValue={false}
            data={[
              { value: false, label: "false" },
              { value: true, label: "true" },
            ]}
          />
          <Button
            marginRight={12}
            style={{ marginRight: "12px", marginTop: "12px" }}
            type="submit"
          >
            Submit
          </Button>
          <Button
            variant="outline"
            style={{ marginTop: "12" }}
            onClick={() => props.modeFunc(!props.mode)}
          >
            Cancel
          </Button>
        </form>
      </Grid.Col>
    </Grid>
  );
};