0

I realise this may be a really simple explanation/answer to this but it's driving me mad. I've got a React component that maps over a state and displays each item in the array as a p tag, but when I change the state using the buttons the UI doesn't change to add or remove any items. I think this has something to do with the way map create a copy of the array and doesn't mutate to original data but I need to have my UI update as the state changes and I just can't work out how to re-run the map function when the state changes.

import React, { useState } from 'react';

export default function Dashboard() {
  const [testState, setTestState] = useState([{ name: 'test' }, { name: 'test' }]);

  function addItem() {
    let obj2 = testState;
    obj2.push({ name: 'test' });
    setTestState(obj2);
  };

  function remItem() {
    let obj2 = testState;
    obj2.pop();
    setTestState(obj2);
  };

  return (
    <div className='main_div'>
      <h2>Dashboard</h2>

      <div>
        {testState.map((item, i) => {
          return (<p key={i}>{item.name}</p>)
        })}
      </div>

      <button onClick={addItem}>ADD</button>
      <button onClick={remItem}>REM</button>

    </div>
  );
};

Thanks in advance,

Matt M
  • 375
  • 1
  • 5
  • 14
  • 1
    `let obj2 = testState;` does not create a copy of the array, it just makes the `obj2` variable point to the same array the `testState` constant points to. Modifying that array is a no-no in React; you must not modify (mutate) an object in state. Instead, create a new array with the added/removed item (see the answers to the [linked question](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) for details). – T.J. Crowder Mar 19 '21 at 10:34
  • 1
    Side note: *Declarations* aren't statements, so they don't have a statement terminator (`;`) after them. The `;` after your declarations for `addItem` and `remItem` aren't needed. (You can put one there, but it's just an empty statement.) You only use `;` at the ends of *statements* that aren't already terminated with a block. (For arcane reasons, what we think of as variable "declarations" are statements, so you do put a `;` after `let x;`.) – T.J. Crowder Mar 19 '21 at 10:36
  • 1
    Thanks, I've sorted it using the info in the linked question, I'm new to react and even newer to hooks so it's taking me a while to get my head around it all. – Matt M Mar 19 '21 at 10:47

0 Answers0