Home > Enterprise >  useState to change quantity in multiple dropdowns
useState to change quantity in multiple dropdowns

Time:11-22

I have several items listed on a page that can be added to a shopping cart. A Product component is being rendered for each product, and there is a form select as part of each component.

                  const [qty, setQty] = useState(1); 
                  ...
                        <Form.Control
                      className="w-100"
                      as="select"
                      value={qty}
                      onChange={(e) => {
                        setQty(e.target.value);
                      }}
                    >

If I useState this way, every product on the page has its Select Value changed when a change is made to the select because it is derived from the qty variable. Since I don't know how many products will be rendered on each page, how can I write a function that will only update the value of the product within the component being changed?

CodePudding user response:

I learned you can setState and initialize it with an object. Once I update the state of a component rendered using the map method, I set the key of the state object with the id of the product. I was able to solve my problem with the code below.

                  const [qty, setQty] = useState({ int: 1 })...

                  <Form.Control
                  className="w-100"
                  as="select"
                  value={item._id in qty ? qty[item.id] : qty.int}
                  onChange={(e) => {
                    setQty({ ...qty, [item._id]: e.target.value });
                  }}
                >

CodePudding user response:

Hint: The useState should be inside the product component, every product component must have its own useState programmatically if you're using the map method.

  • Related