Jabba the Hutt
Jabba the Hutt

Reputation: 664

How to have messages display in correct order?

I have an issue where the messages in my app are not displaying in the correct order after the page is refreshed. The most recent messages are displayed from bottom to top instead of the usual top to bottom (bottom being the most recent). I suspect it has something to do with the reducer function which adds the messages to store.

The debugger is showing that when I send a new message, it shows up at the beginning of the array[0] instead of being the last and newest one. How would I go about fixing this?

The reducer function:

export const addMessageToStore = (state, payload) => {
  const { message, sender } = payload;
  if (sender !== null) {
    const newConvo = {
      id: message.conversationId,
      otherUser: sender,
      messages: [message],
    };
    newConvo.latestMessageText = message.text;
      return [newConvo, ...state];
  }

  return state.map((convo) => {
    if (convo.id === message.conversationId) {
      debugger
      const convoCopy = { ...convo };
      convoCopy.messages.push(message);
      convoCopy.latestMessageText = message.text;
      debugger

      return convoCopy;
    } else {
      return convo;
    }
  });
};

Messages Component:

const Messages = (props) => {
  const { messages, otherUser, userId } = props;

  return (
    <Box>
      {messages.map((message) => {
        const time = moment(message.createdAt).format("h:mm");

        return message.senderId === userId ? (
          <SenderBubble key={message.id} text={message.text} time={time} />
        ) : (
          <OtherUserBubble key={message.id} text={message.text} time={time} otherUser={otherUser} />
        );
      })}
    </Box>
  );
};

Chat Component:

const ActiveChat = (props) => {
  const classes = useStyles();
  const { user } = props;
  const conversation = props.conversation || {};

  return (
    <Box className={classes.root}>
      {conversation.otherUser && (
        <>
          <Header
            username={conversation.otherUser.username}
            online={conversation.otherUser.online || false}
          />
          <Box className={classes.chatContainer}>
            <Messages
              messages={conversation.messages}
              otherUser={conversation.otherUser}
              userId={user.id}
            />
            <Input
              otherUser={conversation.otherUser}
              conversationId={conversation.id}
              user={user}
            />
          </Box>
        </>
      )}
    </Box>
  );
};

const mapStateToProps = (state) => {
  return {
    user: state.user,
    conversation:
      state.conversations &&
      state.conversations.find(
        (conversation) => conversation.otherUser.username === state.activeConversation
      )
  };
};

Upvotes: 1

Views: 294

Answers (1)

Kamal Kumar
Kamal Kumar

Reputation: 11

Try to modify the reducer function as follows:

export const addMessageToStore = (state, payload) => {
    const {message,sender} = payload;
    if (sender !== null) {
        return [{
                id: message.conversationId,
                otherUser: sender,
                messages: [message],
                latestMessageText: message.text
            },
            ...state
        ];
    }

    return state.map((convo) => {
        if (convo.id === message.conversationId) {
            const convoCopy = {
                ...convo,
                latestMessageText: message.text
            };
            convoCopy.messages.unshift(message);

            return convoCopy;
        } else {
            return convo;
        }
    });
};

Upvotes: 1

Related Questions