Hi everyone!
Parrent component has loop and in this loop I have child component.
Child component has two buttons which are shown depending on the state “mode” and when the state changes, the component does not change (does not rerender DOM) the buttons.
Here in example I use AlpinaJS but I tried without it (by @if) and it does not rerender DOM.
(By the loop I have multiple child component)
I have this code:
Parrent component:
@foreach ($product->variations as $key => $item) <div wire:key="{{ $loop->index }}"> <div> <div> <livewire:site.add-to-cart :id1c="$item->id"> </div> <div wire:key="{{ $item->id }}"> @auth // Child component <livewire:site.add-to-favorite :model="$item"> @endauth </div> </div> </div> @endforeach
Child component:
<div x-data="{ mode: '{{ $mode }}' }"> <div x-cloak x-show="mode == 'remove'"> <button wire:click="removeFavorite({{ $model->id }})"> Remove </button> </div> <div x-cloak x-show="mode == 'set'"> <button wire:click="setFavorite()" > Set </button> </div> </div>
Child component:
class AddToFavorite extends Component { public $model; public $mode; public function mount($model) { $this->model = $model; $this->check(); } public function setFavorite() { $favorite = new Favorite([ 'user_id' => auth()->id(), ]); $this->model->favorites()->save($favorite); $this->check(); $this->emit('success', 'Товар добавлен в избранное'); } public function removeFavorite($item_id) { $this->model->favorites()->delete($item_id); $this->check(); $this->emit('success', 'Товар убран из избранных'); } public function check() { if ($this->model->favorites->firstWhere('favoritable_id', $this->model->id)) { $this->mode = 'remove'; } else { $this->mode = 'set'; } } public function render() { return view('livewire.site.add-to-favorite'); } }
Screenshot of DOM
How to fix it?