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?

1 Answer 1

3

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

setGroupState({
  ...groupState,
  content: [...groupState.content, {test: 'test'}],
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.