bilal marifet
bilal marifet

Reputation: 11

redux state change doesnt trigger re-render

this is my state interface

case UPDATE_CONVERSATION_ACTION:
  var list = state.messageList ? state.messageList.length > 0 ? state.messageList : [] : [];
  if(list.length > 0) {
    let val = state.messageList.findIndex(e=>e.postId === action.payload[0])
    if(val !== -1) {
      var messageItem = {} as MessageListItem

      var item = state.messageList[val];
      var messages = item.messages;
      messages.push(action.payload[1]);
      messageItem.messages = messages
      messageItem.postId = action.payload[0];
      list[val] = messageItem
    }else {
      list.push({postId: action.payload[0],messages : [action.payload[1]]})
    }


  }
  else {
    list.push({postId: action.payload[0],messages : [action.payload[1]]})
  }

  return {
    ...state,
    messages: [...state.messages, action.payload],
    messageList :list
  };

<FlatList

    data={this.props.messagesList  ? this.props.messagesList.length > 0  ? this.props.messagesList.find(e=> e.postId === this.state.postId)?.messages ?? [] : [] : []}renderItem={({ item }) => (
        this.renderItems(item)
    )}
    // extraData={selected}
  />

now i listen data from socket i got data dispatch it and update list there is no problem for it bu react didnt render my flatlist component but its changed. only if react render component i press any key in input, react render it message

i did make changes like

var existMessageList = state.messageList.findIndex(e => e.postId === action.payload[0]);

  return {
    ...state,
    messageList : existMessageList !== -1 ? state.messageList.map((val,i)=> val.postId === action.payload[0] ? {...val, messages : state.messageList[i].messages.concat(action.payload[1])} : val) : 
    [...state.messageList,{postId : action.payload[0],messages : [action.payload[1]]}]
  };

it worked thanks

Upvotes: 0

Views: 119

Answers (1)

markerikson
markerikson

Reputation: 67439

You're mutating the existing state with all of the .push() and list[val] = lines. Please don't do that.

See the Redux docs page on "Immutable Update Patterns" and the post The Complete Guide to Immutability in React and Redux for information on how to correctly write immutable updates.

I'd strongly recommend using our official Redux Toolkit package. It has a configureStore API that will catch mutations by default, and the createSlice API actually lets you write "mutating" logic that is safely turned into correct immutable updates.

Upvotes: 1

Related Questions