Search code examples
laravellaravel-livewire

Livewire - Change follow button to unfollow once clicked(persist) without reloading the page. vice versa


As the title says. Is this possible for livewire? I have a piece of code that enables user to follow an author and unfollow using form post which reloads the page after clicking the button. But I am thinking to make it have a better UX by using livewire.

FollowButton.php

class FollowButton extends Component
{
    public $postAuthorId;
    public $authorName;
    public $isFollowed;
    public Post $post;
    public Follow $follow;


    public function mount(){

        $this->postAuthorId = $this->post->author->id;
        $this->authorName = $this->post->author->name;
        $this->isFollowed = (bool) $this->post->author->followedBy(auth()->user());
    }

    public function follow()
    {

        Follow::create([
            'user_id' => $this->postAuthorId,
            'follower_id' => auth()->id()
        ]);;

        session()->flash('success', 'Followed' . $this->authorName);

    }

    public function unfollow()
    {

        # code here..
    }

    public function render()
    {
        return view('livewire.follow-button');
    }
}

follow-button.blade.php

<div>
    
    @if(!$isFollowed)
    
                <button wire:click="follow" class="btn btn-default">
                    Follow
                </button>
    
            @else
    
                <button wire:click="unfollow" class="btn btn-default">
                    Unfollow
                </button>
    
            @endif
      
    </div>

Then in my card.blade.php

@livewire('follow-button', ['post' => $post])

Solution

  • You are setting the property isFollowed on mount method it wont run on every request. Mount method will only run while mounting the component into page.

    So inside the follow method you need to refresh the property

    public function follow()
    {
    
        Follow::create([
            'user_id' => $this->postAuthorId,
            'follower_id' => auth()->id()
        ]);
        $this->isFollowed = (bool) true;
    
    
        session()->flash('success', 'Followed' . $this->authorName);
    
    }
    
    public function unfollow()
    {
        Follow::query()
    ->where([
        [
            'user_id', '=', $this->postAuthorId,
        ],
        [
            'follower_id', '=', auth()->id()
        ]
    ])
    ->delete();
        $this->isFollowed = (bool) false;
    
    
        session()->flash('success', 'Followed' . $this->authorName);
    
    }