Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Livewire, communication between two livewire components

I have 2 livewire components, 1st only displays the session variable of the cart and the 2nd one is just to add items in cart (a very raw form with sku, title, price and qty).

<livewire:shoppingcart :cart="$CartId">

<livewire:order-add-product-form :orderAddProductCartId="$CartId">

Both the components are working fine in itself. But when i add item from the second component, it does update the cart session variable, but the view never updates. I have to refresh the page to see the session variable in the cart view.

Is it possible to connect both the components together. So, when i add item in cart from one component, it automatically updates the view of other component?

Thanks

like image 535
user3765227 Avatar asked Apr 20 '20 19:04

user3765227


People also ask

How do I transfer data from one component to another in livewire?

You can pass data into a component by passing additional parameters into the <livewire: tag. For example, let's say we have a show-post component. Here's how you would pass in a $post model. Alternatively, this is how you can pass in parameters using the Blade directive.

What is wire key in livewire?

Add wire:key . As a final measure, adding wire:key will directly tell Livewire how to keep track of a DOM element. Over-using this attribute is a smell, but it is very useful and powerful for problems of this nature.


1 Answers

From Second component after you add a new product you can emit a event like:

$this->emit('cart:update');

See the docs: Livewire Events

Now you can listen the event from first component and use special action of livewire called $refresh

See the docs: Special Actions

protected $listeners = [
    'cart:update' => '$refresh',
];

I think that solves your problem.

like image 163
Najmus Sakib Avatar answered Oct 23 '22 10:10

Najmus Sakib