Sylar Sylar - 3 months ago 12
SQL Question

Display Last Child in React Iteration

I'm trying to implement a message app, without ActionCable for now. When I map over all messages, I want to show only the last message from that user: instead of showing all messages, from a user, I only show the last. I do not know how to achieve that. I thought I could set the

key
to the
user_id
instead of the
id
.

_messagesRender: function(){
var messages = this.props.message.map( function(m, i){
return(
<li key={m.user_id}>{m.body}</li>
)
});
return(
<div>{messages.length === 0 ? "No messages" : messages}</div>
)
},


This component is on the index page and I'm trying to create a message-like app. Any pointers with React? Rails 5 is used as back end.


Warning: flattenChildren(...): Encountered two children with the same key,
.$2
. Child keys must be unique; when two children share a key, only the first child will be used.


Back end:

@messages = Message.where(to: current_user.id)


Message model:
:id, :to, :user_id, :body


user_id
is who sends/created the message.

Answer

You can try the following:

Message.where(to: current_user.id)
       .order(:created_at)
       .group_by(&:user_id)
       .map{|_, x| x.last}

This should give the last message (by created_at) from each user_id.

As long as you are using Postgresql, you can try distinct on approach:

Message.where(to: current_user.id)
       .order(user_id: :asc, created_at: :desc)
       .select('distinct on (user_id) *')