force component to re-render after redux state change

Viewed 3233

I have a stack navigator with 2 screens, 'Messages' and 'Message'. On the 'Messages'-screen, I want to have an overview of all the people I'm chatting with + the last message in the conversation. I store all conversations in redux, not on the server. My redux state looks like this:

const state = {
    user = [
        {
            userId: 1,
            username: John,
            messages: [...array of messages send to John or from John...]
        },
        {
            userId: 2,
            username: Jane,
            messages: [...array of messages send to Jane or from Jane...]
        }
        ...
    ]
}

On the 'Messages'-screen I have a FlatList component who loops over the users-array in the redux state:

const users = useSelector(state => state.messages.users)

const renderUserItem = user => {
    return (
        <View>
            <Text>{user.username}</Text>
            <Text>{user.messages[user.messages.length-1].message</Text>
        </View>
    )
}

<FlatList
    data={messages}
    renderItem={({item, index}) => renderUserItem(item)} />

This works, I get an overview of the the conversations I have + the last message. When I click on a conversation on the 'Messages'-screen, I'm send to the 'Message'-screen where I have another FlatList with all the messages of this particular conversation. This code is irrelevant but works to.

The problem is: when I add a new message (through the 'Message'-screen), the redux state is updated: (dispatch(addMessage(userId, message)), but when I'm navigate back to the 'Messages'-screen, I don't see the last message, the screen is not re-rendered even though the redux state changed. When I do a hard refresh, it works.

How can I force a screen to re-render when a redux state has changed. I'm using stateless components.

Edit: my reducer:

const initialState = {
    users: []
}

const MessagesReducer = (state = initialState, action) => {
    let array, index, user, messages
    switch (action.type) {
        case 'START_CONVERSATION':
            // action.user is an object which contains userId and username
            array = state.users
            index = array.findIndex(e => e.userId === action.user.userId)
            if (index > -1) {
                // conversation already exists
            } else {
            object = {
                userId: action.user.userId,
                username: action.user.username,
                messages: []
            }
            array.push(object)
            return {
                users: array
            }
        break
        case 'ADD_MESSAGE':
             // action.userId contains the userId of the conversation partner
             // action.message is an object with direction, 
             // message and timestamp in it
             array = state.users
             index = array.findIndex(e => e.userId === action.userId)
             user = array[index]
             user.messages.push({
                 direction: action.message.direction,
                 message: action.message.message,
                 timestamp: action.message.timestamp
             }
             // get the old user object out of the array
             array.splice(index, 1)
             // push the new user object to the beginning of the array
             array.unshift(user)  
             return {
                user: array
             }
        break
        default:
            return state
        break
    }
}
1 Answers

You're mutating state which causes it to appear as if there was no state change at all. This means no re-render.

Change this array = state.users to array = [...state.users].

This will create a new array reference instead of mutating the previous state, which will cause a re-render as expected.


On a second look I noticed a few more issues. These won't stop a re-render, but still mutate the previous state so it should be fixed.

Change this:

user = array[index] // user is still a reference to previous state
user.messages.push({ // messages is still a reference to previous state
  ...

to this:

// Create a new user object based on the previous values
// Then add to the messages array by creating a new array with your new entry
user = {
  ...array[index], 
  messages: [
    ...array[index].messages, 
    {
      direction: action.message.direction,
      message: action.message.message,
      timestamp: action.message.timestamp
    }
  ]
}

// OR
user = {...array[index], messages: [...array[index].messages]}
user.messages.push({...})
Related