0

I did both mode the creation and edit in one form but the problem when I try to edit an element I get the right id value but couldn't retrieve the attributes values.

import { yupResolver } from "@hookform/resolvers/yup";
import { useState, useEffect } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { useParams, useHistory, Link } from "react-router-dom";
import * as yup from "yup";
import {
  getChoice,
  postChoice,
  updateChoice,
} from "../../../../api/remote.api";
import { CustomInput } from "../../../../components/lib";
import { Choice } from "../../../../models";

type Inputs = {
  displayMessage: string;
  value: string;
};

const schema = yup.object().shape({
  displayMessage: yup.string().min(5, "Au minimum 5 chars").required(),
  value: yup.string().min(5, "Au minimum 8 chars").required(),
});

const NewChoice = () => {
  const { id } = useParams<{ id?: string }>();
  const isAddMode = !id;

  let history = useHistory();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [error, setError] = useState<string>();
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<Inputs>({ resolver: yupResolver(schema) });

  const onSubmit: SubmitHandler<Inputs> = (data: Inputs) => {
    setSubmitting(true);
    const choice = new Choice({
      displayMessage: data.displayMessage,
      value: data.value,
      id: Number(id) ? Number(id) : -1,
    });

    submitForm(choice, id)
      .then((chc) => {
        setSubmitting(false);
        history.goBack();
      })
      .catch((e) => {
        const { message } = e.response.data;
        if (message) {
          setError(message);
        }
        setSubmitting(false);
      });
  };

  const submitForm = (choice: Choice, id?: string) => {
    return id ? updateChoice(Number(id!), choice) : postChoice(choice);
  };

  useEffect(() => {
    if (!isAddMode) {
      // get set form fields
      getChoice(Number(id))
        .then(
          (choice: Choice) => {
            setValue("displayMessage", choice.displayMessage);
            setValue("value", choice.value);
          },

          (error) => {
            history.push("/choices");
          }
        )
        .catch((e) => {
          console.log("error catch");
          console.log(e);
        });
    }
  }, [id, isAddMode, setValue, history]);

  return (
    <div className="container m-1">
      <form
        className={`flex-column justify-content-center`}
        onSubmit={handleSubmit(onSubmit)}
      >
        <h1 className="h3 mb-3 fw-normal">Création d'un choix</h1>
        <CustomInput
          register={register}
          label="Message affiché"
          type="text"
          id="displayMessage"
          error={errors.displayMessage?.message}
          placeholder="Display Message"
        />
        <CustomInput
          register={register}
          label="Valeur du choix"
          type="text"
          id="value"
          error={errors.value?.message}
          placeholder="Choice Value"
        />
        {error && <div className="invalid-feedback d-block">{error}</div>}
        <Link to={"."} className="btn btn-small btn-warning mt-3 mr-2">
          Cancel
        </Link>
        <button
          className="btn btn-small btn-primary mt-3"
          type="submit"
          disabled={submitting}
        >
          {isAddMode ? "Création" : "Mise à jour"}
        </button>
      </form>
    </div>
  );
};

export default NewChoice;

and i tried to look a little bit on stack and other websites but couldn't solve this 5 days bug , in a result i just get a blank page with the appropriate id

and the element should be in this file .

export const CustomInput = ({
  register,
  label,
  type,
  id,
  error,
  placeholder,
}: {
  register: any;
  label: string;
  placeholder: string;
  type: string;
  id: string;
  error?: string;
}) => {
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <div className="form-floating">
        <input
          type={type}
          className="form-control"
          id={id}
          placeholder={placeholder}
          {...register(id)}
        />
        {error && <p className="invalid-feedback d-block">{error}</p>}
      </div>
    </>
  );
};

1 Answers1

0

Try a new state:

const [isToUpdate, setUpdate] = useState<boolean>(false);

Add it to useEffect array:

[id,isToUpdate ....]

Add setUpdate to where you are setting values after setValue("value",choice.value);

setUpdate(true);
Mohinder singh
  • 112
  • 1
  • 6
  • it didn't change anything –  Jul 21 '21 at 16:28
  • also there is no value attribute in your input, so how you are handling that. It need to be there to put a value into a input field. You can try by giving value="some temp" in your input tag. – Mohinder singh Jul 21 '21 at 16:31
  • actually it's handled with the setValue method i give my customInput the choice.value , so it should be automatically done –  Jul 21 '21 at 17:42