Home > Software engineering >  ReactJS Adding input values into an array overwrite each other
ReactJS Adding input values into an array overwrite each other

Time:12-22

I have an input that allows users to enter there name and a number, and this is displayed in a list. I am now trying to add these numbers into an array so I can stop duplicate ones from being added.

I think I'm close to a solution as I have the numbers being saved into my variable, however the issue I'm having is that only one number is being saved - and then gets overwritten whenever a new input value is entered. They should all get added into the same array.

Console log of Array after 3 input values are added

const [name, setName] = useState('');
  const [number, setNumber] = useState('');
  const [assigned, takenNumber] = useState([]);

  //
  // Handle adding players to the game
  function handleChange(event) {
    setName(event.target.value);
  }
  function handleNumber(event) {
    setNumber(event.target.value);
  }
  function handleAdd() {
    dispatchListData({ type: 'ADD_ITEM', name, number, id: uuidv4() });
    setName('');
    setNumber('');
    // Save all numbers in an array
    const numbersArray = [assigned];
    numbersArray.push(number);
    takenNumber(numbersArray);

    console.log(numbersArray);
  }

//
// Add players to game form
const AddItem = ({ number, name, onChange, onNumber, onAdd }) => (
  <form>
    <input type="text" value={name} onChange={handleChange} />
    <input type="number" value={number} onChange={handleNumber} min="1" max="20" />
    <button type="button" onClick={handleAdd}>
      Add
    </button>
  </form>
);

CodePudding user response:

It looks like you're nesting your arrays there. assigned is an array, and you are creating numbersArray as an array containing this array.

const assigned = [1]
const numbersArray = [assigned];
// numbersArray is [[1]]

You should use the spread operator ... to spread the elements of assigned into your new array.

const numbersArray = [...assigned];

Here is the documentation for the spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

By the way, you should take a look into the Set structure. It looks like you could solve your problem using it, as it is basically an array that has no duplicates. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

  • Related