I have logic for like/dislike button in two separate livewire components (LikeButton.php/DislikeButton.php)
The problem is I want like/dislike buttons react immediately after clicking
Currently, button looks like this:
<div>
<button wire:click="toggleLike()">Like recipe</button>
{{ $recipe->countLikes() }}
</div>
And now after clicking I need to wait and If my user will have slow internet he’ll be waiting more way longer.
LikeButton.php:
class LikeButton extends Component
{
public Recipe $recipe;
public function toggleLike()
{
$this->dispatch('refresh-dislikes');
// Check if user is authenticated
// if so, get the user
if (! $user = auth()->user()){
return $this->redirect(route('login-page'));
}
// Check if user has already liked recipe
// if true, then return unlike()
$hasLiked = $user->likes()->where([
'recipe_id' => $this->recipe->id,
'liked' => true
])->exists();
if ($hasLiked){
return $this->recipe->unlikeBy($user);
}
// return like()
return $this->recipe->likeBy($user);
}
#[On('refresh-likes')]
public function render()
{
return view('livewire.like-button');
}
}
Is there any solution to fix it by using Alpine.js?