0

I have state set as follows:

  const [groupState, setGroupState] = useState({
    groupId: uuidv4(),
    content: [],
  });

I want to push an object to the 'content' array but am having difficulty. I looked at this answer: How do I update states onchange in an array of object in React Hooks but can't seem to apply it to the problem.

Currently I have:

setGroupState({
  ...groupState,
  ...content.push({test: 'test'})
});

.. but it's not working and I'm getting nowhere.

Can anyone tell me how to get this sorted?

Stef
  • 359
  • 1
  • 4
  • 21

1 Answers1

3

push mutates the array, you should create a new array like so:

setGroupState({
  ...groupState,
  content: [...groupState.content, {test: 'test'}],
});
thedude
  • 9,388
  • 1
  • 29
  • 30
  • Thanks - worked like a treat. Don't know who put the mark down there or what it was for - perfectly reasonable question. 'Research effort' is stated. – Stef Nov 17 '20 at 09:45