3
votes

I've created a livewire component with some input fields, added a for loop to the parent component with the child component inside.

@for($i = 0; $i < $count; $i++)
    @livewire('dashboard.profile.garage-service-list-item', ['garage' => $garage], key($i))
@endfor

Each child component has a delete button. How can the method for this button look like?

1

1 Answers

2
votes

Two ways spring to mind. One being that you display an empty view if the item gets deleted, or you fire an event to refresh all the components that are rendered within that loop.

1: Refreshing the parent

This assumes that the parent component is a Livewire component.

In your parent, you can listen for an event to refresh itself. Simply declare a listener in your parent component (the component that has your @for loop), by adding the following.

protected $listeners = ['refreshParentComponent' => '$refresh'];

refreshParentComponent is the name of the event, you could rename it to something more suitable (that name is probably not a good name), and $refresh is the action -- and in Livewire, the $refresh action is a magical action that simply refreshes the component in its entirety, basically re-rendering it. This would mean that you will get a fresh set of data after deleting the item, and render it all with that data.

To make the event trigger, in your Profile\GarageServiceListItem class, where you delete the item, you can fire, or emit, that particular event - and you can emit it upwards. You can do that by calling the emitUp method.

$this->emitUp('refreshParentComponent');

2: Rendering an empty HTML block

You can add a boolean property to your Livewire-component, for example public $show = true;. Then in the base of your garage-service-list-item view, you start by checking that property.

<div>
    @if ($show) 
        <!-- The rest of your component here -->
    @endif
</div>

Then in the method where you delete the component, simply set $this->show = false; and you're done! The component will render a empty <div> block.