Emit event from mount()

What seems to be the problem:

Emiting an event from mount() on a component is not working. I’m able to emit through a method which is called via wire:click="update" but I also need to emit the event once the component is done loading.

Steps to Reproduce:
Here’s the relevant code…

I have a route:

Route::livewire('/contract-forms/{contract_form}', 'admin.contracts.view-contract-form')->layout('layouts.app-header')->name('contract-forms.view');

I have this in the component for this route:

<?php

namespace App\Http\Livewire\Admin\Contracts;

use App\ContractForm;
use Livewire\Component;

class ViewContractForm extends Component
{
    public $contract_form;

    public function mount(ContractForm $contract_form)
    {
        $this->contract_form = $contract_form->toArray();
        $this->emit('updateTitle', $this->contract_form['title']);
    }

    public function render()
    {
        return view('livewire.admin.contracts.view-contract-form');
    }
}

My layout file, app-header.blade.php calls @livewire('admin.title') component which looks like:

<?php

namespace App\Http\Livewire\Admin;

use Livewire\Component;

class Title extends Component
{
    public $title;

    protected $listeners = ['updateTitle' => 'update'];

    public function render()
    {
        return view('livewire.admin.title');
    }

    public function update($updateTitle)
    {
        $this->title = $updateTitle;
    }
}

Are you using the latest version of Livewire:

Yes, v1.1.0

I came up with a workaround, using blade, but I’m not sure why it works. My current theory, is that even though I’m using the default value of the @yield directive it remains a variable in the view…

In my Livewire title component view I have:

<h1 class="font-semibold pl-6">@yield('title', $title )</h1>

In my Livewire contract form component view I have:

@section('title', $contract_form['title'])
<div>
    <div class="w-full max-w-screen-xl px-6 mt-6 mx-auto">
        <!-- rest of Livewire component view -->
    </div>
</div>

I would rethink your set up, emitting from mount is a huge indicator something needs redone and is a bad pattern to go with. (I thought it just flat out didn’t work, but I could be mistaken)

If it is working, then when the page loads, your Title Component is going through it’s mount procedure and rendering, your whole page is loaded, an ajax request is fired, and the title component is being re-rendered. So you are handling 2 requests to initially show one page. I assume anyway because again, I don’t think it was ever supposed to allow you to do that for this reason.

1 Like

Thajks @xxdalexx Yes, it flat out doesn’t work. I’m using blade now for the initial value and found out @yield('title', $title ) still allows the title to be updated by a Livewire event when It’s updated.