'Updating Array with useState

I'm trying to update a useState array with form values. This code does not work properly. Scratching my head as to why. The function to look at is handleGaugeSubmit. When the loop is finished, the array is only populated with the last element. Many thanks.


const InputFields = () => {
  const [numStrings, setNumStrings] = useState(0);
  const [gauges, setGauges] = useState([]);
  const [nutWidth, setNutWidth] = useState(0.0);

  const runCallback = (cb) => {
    return cb();
  };

  const handleGaugeSubmit = (event) => {
    event.preventDefault();

    for (var i = 0; i < numStrings; i++) {
      setGauges([...gauges, event.target[i].value]);
    }
    return;
  };

  const handleStringNumberSubmit = (event) => {
    event.preventDefault();
    setNumStrings(event.target[0].value);
    return;
  };

  return (
    <div>
      <form onSubmit={handleStringNumberSubmit}>
        <label>Number of strings</label>

        <input type="text" />
        <input type="submit" value="Set number of strings" />
      </form>

      <form onSubmit={handleGaugeSubmit}>
        {runCallback(() => {
          const html = [];
          for (var i = 0; i < numStrings; i++) {
            html.push(
              <>
                <label>String {i + 1}</label>

                <input type="text" />
              </>,
            );
          }
          return html;
        })}

        <input type="submit" value="Submit" />
      </form>
      {gauges.toString()}
    </div>
  );
};

export default InputFields;


Solution 1:[1]

Answer was thanks to @SiddarthSeth. Instead of setting state each pass of the loop, the correct approach is build an array of all elements I want to add, then call setGauges once.

Working solution:

    event.preventDefault();
    const newElements = []
    for (var i = 0; i < numStrings; i++) {
        newElements.push(event.target[i].value);
    }
    setGauges([...gauges, ...newElements]);
    return;
  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max