How to pass variable from child to parent at initial on Laravel livewire?

Viewed 24

I have parent blade link to child component as below.

    <div class="container-fluid">
        {{-- user crud component here --}}
        @livewire('components.employeecrud.employee-crud')
    </div>

And waiting event from child as below.

protected $listeners = [
    'dataToParent'
];

public function dataToParent($value)
{
    dd($value['user_ids']);
}

Then emit from child to parent on mount method.

public function mount()
{
    $this->emitUp('dataToParent',['user_ids'=>[1,2,3]]); 
}

Result return nothing that may cause of parent not finished load yet. Any advice or guidance on this would be greatly appreciated, Thanks.

1 Answers

Sadly, Livewire emits do not work before first render. This is because before then, the JavaScript isn't loaded in. There's a simple fix, however.

On the child component blade:

<div wire:init="init()">
    {{-- Your component here --}}
</div>

In the component class:

public function init() 
{
    $this->emitUp('dataToParent',['user_ids'=>[1,2,3]]); 
}

And then you're set!

A little explanation: wire:init is called when the component is first initialized. We then call a function by the name of "init", and basically have it do what we wanted to do what wasn't possible within the mount method.

Related