How to set only one property in object with useState?

Viewed 1927

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 ?

2 Answers

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.

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" },
      ]
    }
  });
}
Related