Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Hasith's avatar
Level 1

Remove Element from a List using Alpine.JS

I'm trying to implement Sub Tasks adding List. For handling optimistic UI experience i want to handle that in client-side rather than the server. So how can i use Alpine.Js ? When i click delete icon item remove from the UI but in console it's gives me Uncaught TypeError: Cannot read properties of undefined (reading 'subTask'). I @entangle Alpine property to livewire so i can use that when form is submitted. Here is my code?

<div x-data="{
    check: $wire.entangle('needToCheck'),
    newSubs: $wire.entangle('newSubTasks'),
    addSubTask() {
        this.newSubs.push({ id: Math.random(), subTask: '' });
        console.log(this.newSubs);
    },
    removeItem(index) {
        this.newSubs.splice(index, 1);
        this.newSubs = [...this.newSubs]; // Reassign to trigger reactivity
    }
}">
    <x-wui-mini-button 
        rounded 
        secondary 
        icon="plus" 
        x-on:click="addSubTask" 
        x-tooltip.placement.bottom.raw="Add Sub Task" 
    />

    <template x-for="(value, index) in newSubs" :key="value.id">
        <div class="flex items-center justify-between py-2 gap-5">
            <x-wui-input 
                icon="document-text" 
                placeholder="Add Sub Task"
                x-model="newSubs[index].subTask" 
            />
            <x-mary-icon 
                name="m-trash" 
                x-on:click="removeItem(index)" 
                class="text-red-400 hover:text-red-600 cursor-pointer w-6 h-6"
                x-tooltip.placement.top.raw="Remove" 
            />
        </div>
    </template>
</div>
0 likes
3 replies
vincent15000's avatar
Level 63

Your problem seems to be related to newSubs[index].subTask.

The error means that newSubs[index] is undefined.

In the loop, have you tried to just use value instead of newSubs[index] ?

x-model="value.subTask"
1 like
Hasith's avatar
Level 1

@vincent15000 It worked. Thank you !!!

 <template x-for="(sub, index) in newSubs" :key="'sub-task-' + index">         
 <x-input  x-model="sub.subTask" />                  
</template>
                     	
1 like

Please or to participate in this conversation.