• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Post job
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

128
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>
                    );
                  })}
over 1 year ago ยท Santiago Gelvez
Answer question
Find remote jobs