When you click "Send to Parent", the button triggers wire:click="sendMessage"
.
However, the random wire:key="1654651421"
causes the child component to get a new ID.
Livewire then tries to find the old component ID to execute the click handler, but it no longer exists,
resulting in a "Component not found" error in the console.
The component is not stuck displaying the old state and is no longer usable unless the page is refreshed.
class Parent extends Component
{
public $receivedMessages = [];
public $messageCount = 0;
#[On('child-message')]
public function handleChildMessage($message, $from, $time)
{
$this->messageCount++;
array_unshift($this->receivedMessages, [
'message' => $message,
'from' => $from,
'time' => $time
]);
}
}
class ChildWithRandomKey extends Component
{
public $inputText = '';
public $messageCount = 0;
public function sendMessage()
{
if (trim($this->inputText)) {
$this->messageCount++;
$this->dispatch('child-message', [
'message' => $this->inputText,
'from' => $this->getId(),
'time' => now()->format('H:i:s')
]);
$this->inputText = '';
}
}
}
<!-- Child Component Template -->
<div wire:key="{{ rand() }}">
<input type="text" wire:model="inputText" placeholder="Type message...">
<button wire:click="sendMessage">Send to Parent</button>
<span>Messages sent: {{ $messageCount }}</span>
</div>
<!-- Parent includes child -->
<livewire:child-with-random-key />
BROKEN: Random wire:key causes child components to re-initialize on every parent update!