Skip to content

Instantly share code, notes, and snippets.

@jhonoryza
Created September 8, 2021 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhonoryza/406fcfd53b4a79eaa781ef19b2860c88 to your computer and use it in GitHub Desktop.
Save jhonoryza/406fcfd53b4a79eaa781ef19b2860c88 to your computer and use it in GitHub Desktop.

Livewire won't refresh child components as they are isolated from each other, so the way to get them to refresh is a bit of a hack, using keys. What happens is by changing the key, Livewire thinks it's actually a new dom element and so it deletes the old child component and launches a new one with the new key, and as such the new, refreshed, data.

Using the key like I suggested key('vehicle' . $vehicle->id) originally won't work for forcing the child component to refresh. That is why you will see people using keys like you suggested that has time() in it.

I would consider this a bad idea, purely because time changes every time the parent component re-renders. As such all child components that have that in the key will be deleted and replaced, and any dirty state they may have contained will be gone.

What I prefer to do now, is actually create a property on the parent component like public $uniqueKey; and populate that in your mount method $this->uniqueKey = uniqid();.

Then on your child components, set the key to something like this key('vehicle-' . $vehicle->id . '-'.$uniqueKey).

The last step then, is whenever you need to refresh all of the children (like in a listener), in the parent component you would just generate a new key in your method using $this->uniqueKey = uniqid();, which will change the signature of the key for all children, triggering morphdom to delete them all and create new ones.

Doing it this way prevents all components having to be re-initialised every time on the front end, but gives you the option to force changes when needed.

Hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment