Sylar Sylar - 1 year ago 84
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

to the
instead of the

_messagesRender: function(){
var messages = function(m, i){
<li key={m.user_id}>{m.body}</li>
<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,
. Child keys must be unique; when two children share a key, only the first child will be used.

Back end:

@messages = Message.where(to:

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

is who sends/created the message.

Answer Source

You can try the following:

       .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:

       .order(user_id: :asc, created_at: :desc)
       .select('distinct on (user_id) *')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download