Search code examples
laravel-livewirealpine.js

Alpine JS using wrong id


I'm currently making a data table with Laravel Livewire and I use AlphineJS for the confirmation modal. Everything works fine until I paginate to the next page of the data. So here HTML for my delete button for each row :

    <a class="mx-1 text-lg" role="button" x-on:click.prevent="onDelete({{ $article->id }})">
       <i class="fas fa-trash"></i>
       <p x-text="{{ $article->id }}"></p>
    </a>

Here s function for onDelete

    onDelete(id){
      console.log(id);
      this.confirmationModal = true;
      this.id = id;
    },

This is what happens when I try to delete article with an ID of 36, it will console.log the id of the article which is 36 Before Navigation

Then I navigate to the next page and try to delete the article with an ID of 46 but the console.log remains 36, I was expecting 46 After Navigation

How to solve this problem?


Solution

  • Change x-on:click to wire:click

    <a class="mx-1 text-lg" role="button" wire:click="$emit('onTrashIcon',{{ $article->id }})">
       <i class=" fas fa-trash"></i>
    </a>
    

    and add listener function x-data + don't forget to x-init="listen()"

        listen() {
          window.livewire.on('onTrashIcon', articleId => {
            this.id = articleId;
            this.confirmationModal = true;
          })
        }