What seems to be the problem:
I want to add items to an array and I’m doing it using a text box and when I click the add button, the I display the list by looping over the array and display the text in a textbox along with a remove button.
When I delete an item sometimes all items disappear at once and when I click the delete button for any that item remains and some other item gets removed.
Steps to Reproduce:
Add some text to the input box and click add
Then add another item
now try to remove any one item
Are you using the latest version of Livewire: yes
Do you have any screenshots or code examples:
SomeComponent.php
class SomeComponent extends Component
{
public $text;
public $items = [];
public function render()
{
return view('livewire.some-component');
}
public function addText()
{
array_push($this->items, ['text' => $this->text]);
//Alternative:
// $this->items[] = ['text' => $this->text];
}
public function removeText($index)
{
$this->items = array_splice($this->items, $index, 1);
//Alternative:
//unset($this->items[$index]);
}
}
The some-component.blade.php
<div>
<ul>
@foreach($items as $item)
<li wire:key="Item{{$loop->index}}">
<input wire:model="items.{{$loop->index}}.text" type="text"/>
<button wire:click="removeText({{$loop->index}})" type="button">X</button>
</li>
@endforeach
</ul>
<div>
<input wire:model="text" type="text"/>
<button wire:click="addText" type="button">Add</button>
</div>
</div>