Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

very, very new to React. first stack overflow post.

been coding over 12 hrs, probably a small mistake. Trying to work on the U of a CRUD app. My edit form keeps saying things are undefined. IT is saying that "name" under the "medicine name" label is undefined.

import React, { useEffect, useState } from "react";
const EditMedicineForm = (props) => {
  const initialFormState = { id: null, name: "", directions: "" };
  const [medicine, setMedicine] = useState(props.currentMedicine);

  useEffect(() => {
    setMedicine(props.currentMedicine);
  }, [props]);

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setMedicine({ ...medicine, [name]: value });
  };

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        if (!medicine.name || !medicine.description) return;
        props.updateMedicine(medicine.id, medicine);
        setMedicine(initialFormState);
      }}
    >
      <label>medicine name</label>
      <input
        type="text"
        name="name"
        value={medicine.name}
        onChange={handleInputChange}
      />
      <label>directions</label>
      <input
        type="text"
        name="directions"
        value={medicine.directions}
        onChange={handleInputChange}
      />
      <button>Update medicine</button>
      <button
        onClick={() => props.setEditing(false)}
        className="button muted-button"
      >
        Cancel
      </button>
    </form>
  );
};
export default EditMedicineForm;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

Before that use a property of object please check the object first. The object has to have content. Like this:

if (medicine && (!medicine.name || !medicine.description)){
  return; 
}

Look for that at your code and change them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...