laravellaravel-livewire

Livewire component unable to emit data


resources/views/livewire/reset-user-password.blade.php

<button style="text-align: right" type="submit" class="btn btn-outline-primary" id="submitBtn"
    onclick="confirm('Confirm reset password?') || event.stopImmediatePropagation()" wire:click="resetPassword">
       {{ __('Submit') }}
</button>

app\Livewire\ResetUserPassword.php

class ResetUserPassword extends Component{
   public function render(){
    return view("livewire.reset-user-password");
   }

   public function clear(){
    $this->userId = "";
   }

   public function resetPassword(){
       $resultMsg = "Password of user name: xxxxxx successfully reset.";
       $this->emit("successMsg", $resultMsg);
   }
}

resources/view/js/resetUserPasswordJS.blade.php

<script>
   document.addEventListener('livewire:load', function() {
       Livewire.emit('successMsg', (data) => {
       alert(data);
       });
   })
</script>

In Laravel livewire, when I try to trigger the function from blade component, it could not work on emitting events. Since I am not familiar on how to use livewire, may I ask how can I change the script in order to have the emit working?

I have read the docs from Livewire but could not know what will be the best solution so may want some help.


Solution

  • In the blade you can use wire:click="$dispatch('resetPassword')"

    For the Livewire component

    use Livewire\Attributes\On;
    
    #[On('resetPassword')]
    function resetPassword(){
       $resultMsg = "Password of user name: xxxxxx successfully reset.";
       $this->dispatch('successMsg', $resultMsg);
    } 
    

    and for JS

    <script>
        document.addEventListener('livewire:init', function() {
            $wire.on('successMsg', (event) => {
                alert(data);
            });
       });
    </script>
    

    Here is the Livewire V3 documantation for more information on firing and listening to events

    Hope i could help you