Refreshing Paginated List After Update or Delete

I have a livewire component that loads a list of data on my page.
The data being loaded is paginated.
Each row has a delete button.
When I click delete the item is deleted but the view itself is not rerendered.
The deleted item still shows on the page till after refresh.

This is my code:
https://pastebin.com/M231qYL5

<?php

namespace App\Http\Livewire\Sections;

use App\Models\Section;
use Exception;
use Livewire\Component;
use Livewire\WithPagination;

class Rows extends Component
{
    use WithPagination;

    public $name;

    protected $paginate = 10;

    public $listeners = ["sectionAdded"];

    public function add()
    {
        $this->validate([
            "name" => "required"
        ]);

        try {
            $section = new Section();
            $section->name = $this->name;
            $section->save();

            session()->flash("message", "Section was added successfully.");
        } catch (Exception $e) {
            session()->flash("error", $e->getCode() . ": " . $e->getMessage());
        }
    }

    public function remove($id)
    {
        $section = Section::find($id);
        $section->delete();
    }

    public function sectionAdded()
    {
    }

    public function mount()
    {
    }

    public function render()
    {
        return view('livewire.sections.rows', [
            'sections' => Section::paginate($this->paginate),
        ]);
    }
}

Just started playing with Livewire and the simplest way I found (without getting into vue) is to just re-render the component (so it displays the updated results).

You can call the render method again using Livewire Listeners. You can do this both for the added and deleted methods, use

protected $listeners = [‘sectionAdded’ => ‘render’, 'sectionDeleted => ‘render’];

// Syntax for listeners is $listeners = [‘event_name’ => ‘method_to_call_on_event’];
and inside the add method, just emit the event using $this->emitSelf(‘sectionAdded’); & $this->emitSelf(‘sectionDeleted’);

This way every time the event is triggered, livewire will re-render the component with updated results without page refresh.

3 Likes