1

I have a strange problem with Redux and React. The state changes properly and in reducer I also get the right new state but after the changes the component will not rerender.

 case 'READ_MESSAGE_FROM_USER':
                {
                    let copyChat = Object.assign({}, { state: state })
                    let chatHistory = copyChat.state
                    const userIndex = chatHistory.findIndex(item => item.chatThreadId === action.mes.threadId)
                    if (userIndex != -1) {
                        if (chatHistory[userIndex].conversation) {
                            let messages = [...chatHistory[userIndex].conversation]
                            const msgIndex = messages.findIndex(item => item.id === action.mes.messageId)
                            console.log(chatHistory[userIndex].conversation[msgIndex], "READ_MESSAGE_FROM_USER")
                            if (msgIndex != -1) {
                                chatHistory[userIndex].conversation[msgIndex].readDate = action.mes.date
                            }
                        }
                    }
                    return chatHistory
                }

1 Answers1

0

Latest redux template npx create-react-app my-app --template redux that comes with redux toolkit that comes with immer

To set your state without using immer you can do:

case 'READ_MESSAGE_FROM_USER': {
  return state.map((historyItem) =>
    historyItem.chatThreadId !== action.mes.threadId
      ? historyItem
      : {
          ...historyItem,
          conversation: historyItem.conversation.map(
            (conversationItem) =>
              conversationItem.id !== action.mes.messageId
                ? conversationItem
                : {
                    ...conversationItem,
                    readDate: action.mes.date,
                  }
          ),
        }
  );
}
HMR
  • 37,593
  • 24
  • 91
  • 160