FounderStartup's avatar

livewire chat app issue

I am new to livewire and trying to develop a chat app ( with poll ). When I submit a message the page goes blank though the data has been saved and if I refresh then it shows in the chat. Any help ?

My component is :

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Conversation;
use App\Models\Message;

class ListConversationAndMessages extends Component
{

    public $body;

    public $selectedConversation;

    public function mount()
    {
        if (session()->has('selectedConversation')) {
            return $this->selectedConversation = session('selectedConversation');
        }

        $this->selectedConversation = Conversation::query()
            ->with('messages.user')
            ->where('sender_id', auth()->id())
            ->orWhere('receiver_id', auth()->id())
            ->first();
    }

    public function sendMessage()
    {
        Message::create([
            'conversation_id' => $this->selectedConversation->id,
            'user_id' => auth()->id(),
            'body' => $this->body
        ]);

        $this->reset('body');

        $this->viewMessage($this->selectedConversation->id);
    }

    public function viewMessage($conversationId)
    {
        $this->selectedConversation = Conversation::findOrFail($conversationId);
    }

    public function render()
    {
        $conversations = Conversation::query()
            ->with('receiver','messages')
            ->where('sender_id', auth()->id())
            ->orWhere('receiver_id', auth()->id())
            ->get();

        return view('livewire.list-conversation-and-messages', [
            'conversations' => $conversations
        ]);
    }

}

blade :

     <!-- Message Content Inner / End -->
                    <form wire:submit.prevent="sendMessage" action="#">
                        <div class="message-reply">
                            <input wire:model.defer="body" type="text" name="message" placeholder="Type Message ...">
                            <span class="input-group-append">
                                <button type="submit" class="button ripple-effect">Send</button>
                            </span>
                        </div>
                    </form>

When I submit a message the page goes blank though the data has been saved and if I refresh then it shows in the chat.

Any help ?

0 likes
7 replies
Sinnbeck's avatar

Check the browser console if there are errors there

1 like
Sinnbeck's avatar

@FounderStartup if you comment out this line, does anything change?

//$this->viewMessage($this->selectedConversation->id);
1 like
Snapey's avatar

i would change this line

$this->reset('body');

to

$this->body = null;
1 like
Snapey's avatar

in mount, you are loading messages related to selected conversation, but after saving new message, you are not loading the messages

1 like

Please or to participate in this conversation.