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,