hirethunk / verbs

Verbs is an event sourcing package for PHP artisans
https://verbs.thunk.dev
MIT License
412 stars 32 forks source link

[Bug]: Data does not refresh automatically in livewire #181

Open johnrudolph opened 1 week ago

johnrudolph commented 1 week ago

What happened?

If you update data on a livewire component from a Verbs event, the data doesn't always refresh immediately. Once you refresh the page it works. I think this has to do with the sequence of events with Verbs events not being committed until the end of the request?

But even adding Verbs::commit() and $wire:refresh does not help.

How to reproduce the bug

Build a simple form in Livewire like this:

    public function save()
    {
        $this->user->update([
            'name' => $this->user_name,
        ]);
    }

and a blade component like this:

    <p>{{ $this->user_name }}</p>
    <input wire:model="user_name" /> 
    <button wire:click="save">Save</button>

Obviously when you click save, the p tag updates and shows the new name in the database. Now, instead of directly updating the user in the save function, fire an event for UserNameUpdated, which works like this:

    public function save()
    {
        UserNameUpdated::fire(
            user_id: $this->user->id,
            name: $this->user_name,
        );
    }
class UserNameUpdated extends Event
{
    public int $user_id;

    public string $name;

    public function handle()
    {
        User::find($this->user_id)->update([
            'name' => $this->name,
        ]);
    }
}

When you do this, the p tag showing the name does not update until you refresh the page. Even if you add a commit after the event, it doesn't refresh:

    public function save()
    {
        UserNameUpdated::fire(
            user_id: $this->user->id,
            name: $this->user_name,
        );

        Verbs::commit();
    }

Package Version

0.5.1

PHP Version

8.2

Laravel Version

11.20.0

Which operating systems does with happen with?

macOS

Notes

No response