• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

273
Views
how can I get values from a dynamic input fields and structure it in react js state

From the below UI I want to output something like this on my state.

[{title: 'Barnes Chapman', options:{extra large: '8.0', ketchup: '1.00', extra tomato: '2' } }]

enter image description here

I have created a function but the function is not working properly, the state is only updated 2 times when I want to update the state 3rd time it is not updating, I have debugged and the conditions are working but the previous value is not storing and 3rd time the state is not updating anymore.

 const getIngredients = (e, product) => {
    setIngredients((prevValue) => {
      const isExist = prevValue.find((item) => item.title === product.title);
      console.log(isExist);
      console.log({
        ...isExist?.options,
        title: e.target.name,
        price: e.target.value,
      });
      if (isExist) {
        isExist.options = {  // Problem is here previous value is not storing 
          ...isExist.options,
          title: e.target.name,
          price: e.target.value,
        };
        return prevValue;
      }
      return [
        ...prevValue,
        {
          title: product.title,
          options: { title: e.target.name, price: e.target.value },
        },
      ];
    });
  };

JSX code: the checkbox values are dynamic

 {product.ingredients.map((ingredient) => {
                    return (
                      <li onChange={(e) => getItemValues(e.target, product)}>
                        <label className="container_check">
                          {ingredient.title}  // "ketchup"
                          <span>+ $2</span>
                          <input
                            type="checkbox"
                            value={ingredient.price} // "1"
                            name={ingredient.title} // "ketchup"
                          />
                          <span className="checkmark"></span>
                        </label>
                      </li>
                    );
                  })}
about 3 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error