Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
How to handle nested elements in hooks?
const [mealData, setMealData] = useState({
title: '',
description: '',
category: '',
price: '',
mealIMG: null,
ingredients: [],
})

So i have this state object in my component. When i click on add button the state becomes like this: (let's say we clicked twice)

{
title: '',
description: '',
category: '',
price: '',
mealIMG: null,
ingredients: [
        {ingredient:"", qty:"", unit:"", id:id},
        {ingredient:"", qty:"", unit:"", id:id},
  ],
}

Now on the change event handler i want to update the state without mutating the other i am using this function to achieve the work but it's not working:

const handleIngredients = (e, index) => {
  const { name } = e.target
  setMealData((prev) => {
    return {
      ...prev,
      ingredients: [
        {
          ...prev.ingredients[index],
          [name]: e.target.value,
        },
      ],
    }
  })
}

Any clue please?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

const { useEffect, useState } = React;

function Example() {

  const [ state, setState ] = useState({
    title: '',
    description: '',
    category: '',
    price: '',
    mealIMG: null,
    ingredients: []
  });

  useEffect(() => {
    const json = JSON.stringify(state.ingredients);
    console.log(json);
  }, [state]);

  function handleChange(e) {
    
    // Grab our needed props from the
    // changed input
    const {
      name,
      value,
      parentNode: { id },
    } = e.target;

    // Get ingredients from state
    const { ingredients } = state;

    // Is there is an object in the ingredients
    // where the id matches the id from the props
    const found = ingredients.find(i => {
      return i.id === id;
    });

    // If there is...
    if (found) {
      
      // Create a new object using the found
      // object, and the name/value of the input
      const updated = { ...found, [name]: value };
      
      // `filter` out all the objects where the object id
      // doesn't match the id from props
      const filtered = ingredients.filter(i => {
        return i.id !== id
      });
      
      // Set the new state using the filtered
      // array, and the updated object
      setState({
        ...state,
       ingredients: [ ...filtered, updated ]
      });
    
    // If an object isn't found
    } else {

      // Add a new object to the ingredients array
      setState({
        ...state,
        ingredients: [
          ...state.ingredients,
          { id, [name]: e.target.value }
        ]
      });

    }

  }

  return (
    <div>
      <Input id="1" handleChange={handleChange} />
      <Input id="2" handleChange={handleChange} />
    </div>
  );

};

function Input({ id, handleChange }) {
  return (
    <div className="set" id={id} onChange={handleChange}>
      Ingredient: <input name="ingredient" />
      Qty: <input name="qty" />
      Unit: <input name="unit" />
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
input { display: block; } 
.set { display: inline-block; margin-bottom: 1em; border: 1px solid #454545; padding: 0.2em; width: 45%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!