Search code examples
phplaraveleloquentlivewireslaravel-livewire

Laravel Livewire Same Component Two Items Sync in One Page


I made follower component.

If visitor follows a author, then component will show Following and if not, it will show Follow.

I put follower component in two places of page.

-follower component.

<div>
    <a href="javascript:void(0);" class="follow_btn" wire:click="toggle">{{$following? 'Following': 'Follow'}}</a>
</div>

public $following = true; public $post;

public function mount($post)
{
    $this->post = $post;
}
public function render()
{
    if(Auth::check()&&user()->isFollowing($this->post->user))
    {
        $this->following = true;
    }else {
        $this->following = false;
    }
    return view('livewire.following');
}
public function toggle()
{
    user()->toggleFollow($this->post->user);
}

I am using this component in two places in one page.

<livewire:follower :post="$post">
...
<livewire:follower :post="$post">

When I click one component, it was toggled and worked well.

But the other component keeps old state.

How can I sync them?

Thank you


Solution

  • I had to emit refresh event.

    protected $listeners = [
         'followingRefresh' => '$refresh',
    ];
    
    public function mount($post)
    {
        $this->post = $post;
    }
    public function render()
    {
        if(Auth::check()&&user()->isFollowing($this->post->user))
        {
            $this->following = true;
        }else {
            $this->following = false;
        }
        return view('livewire.following');
    }
    public function toggle()
    {
        user()->toggleFollow($this->post->user);
        $this->emit('followingRefresh'); //emit event
    }
        
    

    Hope this helps someone.