Live-wire - real time chat not responding correctly

Viewed 823

I'm trying live-wire to see how to implement it in my upcoming project. The idea is a simple chat ( user enters a body of text and click send then the message will be at the bottom of the chat)

So far everything works fine till I hit the click send button.

Here is picture before I click on send enter image description here

and here is what happens after I click send

enter image description here

I feel like the issue is in this part of code where I send the message to the live-wire blade

  @foreach ($messages as $message)
            @if($message->isYou())
                <livewire:conversations.conversation-message-own :message="$message" :key="$message->id" />
            @else
                <livewire:conversations.conversation-message :message="$message" :key="$message->id" />
            @endif
        @endforeach

here is the component

public $body= "";
public $conversation;

public function mount(Conversation $conversation)
{
    $this->conversation = $conversation;
}

public function reply()
{
    $this->validate([
        'body' => 'required',
    ]);
    $message = $this->conversation->messages()->create([
        'user_id' => user()->id,
        'body' => $this->body,
    ]);
    $this->emit('message.created',$message->id);
    $this->body = "";
}
public function render()
{
    return view('livewire.conversations.conversation-reply');
}

}

last is listening to the event component:

 class ConversationMessages extends Component
{

public $messages;

public function mount(Collection $messages)
{
    $this->messages = $messages;
}

public function render()
{
    return view('livewire.conversations.conversation-messages');
}
protected function getListeners()
{
    return [
    'message.created' => 'prependMessage',
    ];
}

public function prependMessage($id)
{
    $this->messages->prepend(Message::find($id));
}

} the issue in the inspect log is

Uncaught (in promise) TypeError: Cannot read property 'data' of null but I think it's not related to the chats data!

Thanks in advance

1 Answers

The problem is in the keys passed to the conversation-messages components. Livewire breaks trying to render these components, even if separated with ifs. You will need to generate different keys, like a string 'message-own-' . $message->id and 'message-'. $message->id . I tested your code with rand() data:

@foreach ($messages as $message)
    @if($message->isOwn())
        <livewire:conversations.conversation-message-own :message="$message" :key="rand() * $message->id" />
    @else
        <livewire:conversations.conversation-message :message="$message" :key="rand() * $message->id" />
    @endif
@endforeach
Related