I'm using Livewire, and more specifically Volt and Alpine. I've always use the mount() method to initialize my variables, but recently something odd happened. This is replicable, and I think it has to do with my understanding (or lack of) of the lifecycle in Livewire.
A portion of my volt code is as follows:
new
#[Layout('components.layouts.admin')]
class extends Component {
// Info para select
public $tiposJuego;
public $otros;
public $open = false; // Added to manage toggle state
public function mount() {
$this->tiposJuego = TipoJuego::all();
$this->otros = collect([1,2,3,4,5,6]); // Initialize $otros
}
public function toggle() {
$this->open = !$this->open;
}
}; ?>
<div>
<x-h1 label="Template Reglas" class="mb-6" />
<p>{{ $tiposJuego }}</p>
<p>{{ $otros }}</p>
<div x-data="{ open: $wire.entangle('open') }">
<button wire:click="toggle">Toggle</button>
<div x-show="open">
<p>This content is toggled.</p>
</div>
</div>
</div>
So in mount() I'm initializing $tiposJuego, I'm gonna use it later for a select. But now I'll only display the data.
This works as intended the time it renders.
Now there's my Alpine. If I don't entangle the Laravel variable, it works, but if I entangle it, and use the toggle() method to change its value, the data in $tiposJuego is lost. It's like if it was initializing the whole component without calling the mount() method.
Checking the documentation it says the mount() method is called when the component is created. I'm okay with that, and I can solve my problem if I use the boot() method instead.
So I have some questions:
-
Why does it clears the variable that comes from the relation ($tiposJuego) while the $otro which is a fixed value -as you can see in the code- remains the same, after the toggle() function is called?
-
What is the correct way? I have used mount() for several years, should I use boot() instead?
-
Now, wierder... but I think it has to do with how Alpine works... If I DON'T entangle the variable, the value in the $tiposJuego remains the same.