Home > front end >  How do I add user input inside an object array with useState?
How do I add user input inside an object array with useState?

Time:01-02

I am new to React and I am currently building a recipe website to add/edit/delete recipes inside a database (Django). My issue is I have my backend set up and the proper JSON format, but I do not know how to properly manipulate the data on my front end to eventually send to my back end. Code and problem is as follows.

JSON

{
        "id": 1,
        "name": "Pizza",
        "description": "Good Pizza",
        "ingredients": [
            {
                "ingredients": "cheese"
            }
        ]
    }

React


const Home = () => {
  const [item, setItem] = useState({
    name: "",
    description: "",
    ingredients: [{
        ingredients: ''
    }],
  });

  const handleInputChange = (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    if (name === "ingredients") {
      setItem({ ingredients: [{ [name]: value }] });
    } else {
      setItem({ [name]: value });
    }
  };

  console.log(item);  // using to keep track of what has changed

  return (
    <div>
      <form>
        <input
          name="name"
          type="text"
          value={item.name}
          onChange={handleInputChange}
        />
        <input
          name="ingredients"
          type="text"
          value={item.ingredients[0].ingredients} // im like 200% sure this is wrong...
          onChange={handleInputChange}
        />
      </form>
    </div>
  );
};

export default Home;

Submitting user input to name, or description is working fine, but I am running into all sorts of issues as soon as I try to add ingredients, and I cannot seem to find the right way forward. I understand my code is minimal on the react side, but I wanted to get the ingredients down before I proceeded to adding anything else (adding extra inputs, styling, REST operations). Thank you!

CodePudding user response:

So I would remove this ingredients duplicate, so taht it is a simple string array:

    {
        "id": 1,
        "name": "Pizza",
        "description": "Good Pizza",
        "ingredients": ["cheese"]
    }

Then your modification of the state value would be as simple as adding an object to an array:

const addIngredient = (value) => {
    setItem(prevItem => {
        return (
            ...prevItem,
            ingredients: [...prevItem.ingredients, value],
        );
    });
}
  • Related