Skip to content Skip to sidebar Skip to footer

How To Modify Array Within Object In React Component State

I have the following state in my app: const [activeChats, setActiveChats] = useState([ { id: 1, name: 'Luciana Gutierrez', role: 'HR Manag

Solution 1:

You need to return a new array for setActiveStates being particularly careful not to mutate the nested object that you are updating. A long hand approach is to findIndex() of the item you want to update, then use this index to spreadslice()s of the array before and after the item in question, and also retrieve and clone the item itself and any nested object properties to return a copy.

const newMessages = [{ content: 'new1', received: true, date: '10:21 AM' }, { content: 'new2', received: true, date: '10:22 AM' }];
const itemId = 1;

setActiveChats(prevState => {
  const index = prevState.findIndex(({ id }) => id = itemId);
  const item = prevState[index];
  return [
    ...prevState.slice(0, index),
    { ...item, messages: [...item.messages, ...newMessages] },
    ...prevState.slice(index + 1)
  ];
});

Solution 2:

It's a little bit tedious to do this with nested structures but something like this should work:

setActiveChats(
      activeChats.map((activeChat, idx) => {
        // Add to the first entryif (idx === 0) {
          return {
            ...activeChat,
            // assumes `newMessages` is an array of new messagesmessages: [...activeChat.messages, ...newMessages]
          };
        }
        return activeChat;
      })
    );

See a full working example here.

Post a Comment for "How To Modify Array Within Object In React Component State"