2

I have an object as state in react:

{course: {…}, userIDs: Array(2), usersNumber: 2}

Where course is such an object:

price : 100
promotion : null
comments : []

What I want to do is add a new object to the comments array and leave all other properties unchanged. How to do it with useState ?

Monoxyd
  • 406
  • 1
  • 7
  • 18
  • Could you add whole component? – Danial Aug 30 '21 at 14:20
  • In general, you would create a new object, deep copy your current state object into the new object, make the changes in the new object, and then setState to the new object. – dikuw Aug 30 '21 at 14:23

2 Answers2

-1

The setState function also accepts a function that receives the current state. So you can do something like this:

setData(data => {
  const updatedData = { ...data };
  updatedData.course.concat(newComment);
  return updatedData;
});

First, copy the data variable so that you don't change the existing reference. Then concat the new comment to the course property. Finally, return the new data object.

Chris
  • 6,331
  • 1
  • 21
  • 25
-1

You can use the spread operator to spread all the current values and only add a new comment to the new comments array:

const [state, setState] = useState({
  course: {
    price: 100,
    promotion: null,
    comments: [],
  },
  userIDs: [],
  usersNumber: 2
});

function updateState() {
  setState((currState) => ({
    ...currState,
    course: {
      ...currState.course,
      comments: [
        ..currState.course.comments,
        { thisIsANew: "comment" },
      ]
    }
  });
}
Ross Allen
  • 43,772
  • 14
  • 97
  • 95