Debug School

rakesh kumar
rakesh kumar

Posted on

How to communicate events between component in livewire

To handle the $queryParams passed via the dispatch method in your Livewire component and access it on the frontend without refreshing or reloading, you can follow these steps:

Livewire Component: Dispatch the event with the parameters.

JavaScript Listener: Listen for the dispatched event and handle the parameters on the frontend.

Dispatching Event in Livewire Component
In your Livewire component, you dispatch an event with the query parameters:

$this->dispatch('refreshComponent', $queryParams);
Enter fullscreen mode Exit fullscreen mode
public function paytm($paymentMethodValue)
            {
                  Log::info("paytm hua hain");  
               $queryParams = [
                'totalSum' => 5,
                'gst' => 2,
                'sumGst' => 10,
                'totalItems' => $this->item->count(),
                'cartIds' => $this->cartIds,
                'userId' =>$this->userId,
                'username' => $this->username,
                'useremail' => $this->useremail,              
                'allcartId' => $this->allcartId,
                'influencer_email' => $this->influencer_email,
                'influencer_name' => $this->influencer_name,
                'influencer_admin_id' => $this->influencer_admin_id,
                // Add more parameters as needed
            ];
            Log::info("paytm hua hain");  
            $this->dispatch('refreshComponent',$queryParams);// without refresh or reload      

            }
Enter fullscreen mode Exit fullscreen mode

Listening for the Event on the Frontend
In your Blade view or JavaScript file, you need to set up an event listener to catch the dispatched event and handle the query parameters.

Using Alpine.js (if you're using Alpine.js with Livewire)

<div x-data="{ queryParams: {} }" x-init="
    Livewire.on('refreshComponent', event => {
        console.log('Event:', event); // Check if the event is being received
        console.log('Query Params:', event.detail.params); // Log the parameters
        this.queryParams = event.detail.params;
    });
">
    <!-- Your Livewire component -->
    @livewire('your-livewire-component')
</div>
Enter fullscreen mode Exit fullscreen mode

Using Vanilla JavaScript
If you are not using Alpine.js, you can use plain JavaScript to listen for the Livewire event:

<div id="livewire-container">
    <!-- Your Livewire component -->
    @livewire('your-livewire-component')
</div>
Enter fullscreen mode Exit fullscreen mode
<script>
    document.addEventListener('livewire:load', function () {
        Livewire.on('refreshComponent', function (queryParams) {
            console.log('Query Params:', queryParams);
            // Handle your logic here
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Explanation
Livewire Component: You use $this->dispatch('refreshComponent', $queryParams); to dispatch an event named refreshComponent along with the query parameters.

Frontend: When the Livewire component loads, you set up an event listener for the refreshComponent event. The callback function receives the queryParams and you can handle them as needed, such as updating the DOM or triggering other JavaScript actions.

One Practical Example

Example Usage
Let's consider a practical example where you want to update a section of the page with the received query parameters.

Livewire Component (YourLivewireComponent.php)

<?php

use Livewire\Component;

class YourLivewireComponent extends Component
{
    public $queryParams = [];

    public function mount()
    {
        // Initialize or load your query params
        $this->queryParams = ['foo' => 'bar', 'baz' => 'qux'];
    }

    public function updateQueryParams()
    {
        // Update queryParams as needed
        $this->queryParams = ['foo' => 'newFoo', 'baz' => 'newBaz'];
        $this->dispatch('refreshComponent', $this->queryParams);
    }

    public function render()
    {
        return view('livewire.your-livewire-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

Blade View (your-livewire-component.blade.php)

<div>
    <button wire:click="updateQueryParams">Update Query Params</button>
</div>
Enter fullscreen mode Exit fullscreen mode

JavaScript (in your Blade view or an external file)

<div id="livewire-container">
    @livewire('your-livewire-component')
</div>
Enter fullscreen mode Exit fullscreen mode
<script>
    document.addEventListener('livewire:load', function () {
        Livewire.on('refreshComponent', function (queryParams) {
            console.log('Query Params:', queryParams);
            // Example: Update a part of the page with new query params
            document.getElementById('query-params-display').innerText = JSON.stringify(queryParams);
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode
<div id="query-params-display"></div>
Enter fullscreen mode Exit fullscreen mode

With this setup, when you click the "Update Query Params" button, the Livewire component updates the query parameters, dispatches the refreshComponent event, and the JavaScript listener catches this event to update the DOM with the new query parameters.

Using livewire

Reference

Image description

Image description

Image description

Image description

Using alpine js
Reference

Image description

Image description

Reference

Top comments (0)