Created
April 8, 2024 11:45
-
-
Save zechtz/332ddfd94c1fe6a0bbda0ed02f20ee43 to your computer and use it in GitHub Desktop.
Phoenix Downvote Live Component styled using tailwind css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule LiveWeb.Downvote do | |
use LiveWeb, :live_component | |
alias Live.FAQs | |
@impl true | |
def update(assigns, socket) do | |
{:ok, assign(socket, assigns)} | |
end | |
@impl true | |
def render(assigns) do | |
~H""" | |
<button | |
id="downvote-button-#{@faq_id}" | |
phx-click="downvote" | |
phx-target={@myself} | |
phx-value-id={@faq_id} | |
class="bg-white p-2 rounded shadow-md flex flex-col items-center justify-center hover:bg-gray-100 focus:outline-none" | |
> | |
<svg | |
xmlns="http://www.w3.org/2000/svg" | |
class="h-6 w-6 text-gray-700" | |
fill="none" | |
viewBox="0 0 24 24" | |
stroke="currentColor" | |
transform="rotate(180)" | |
> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" /> | |
</svg> | |
<span class="text-gray-700 text-sm font-semibold"><%= @faq.downvotes %></span> | |
</button> | |
""" | |
end | |
@impl true | |
def handle_event("downvote", %{"id" => faq_id}, socket) do | |
case FAQs.dislike(faq_id) do | |
{:ok, updated_faq} -> | |
notify_parent({:downvoted, updated_faq}) | |
{:noreply, | |
socket | |
|> put_flash(:info, "Downvoted successfully")} | |
{:error, _reason} -> | |
{:noreply, socket |> put_flash(:error, "Vote count cannot be less than zero")} | |
end | |
end | |
# update parent component after successfull downvote to update the UI | |
defp notify_parent(msg), do: send(self(), {__MODULE__, msg}) | |
end | |
#Parent Component Handle info callback will look like this | |
@impl true | |
def handle_info({LiveWeb.Downvote, {:downvoted, faq}}, socket) do | |
{:noreply, stream_insert(socket, :faqs, faq)} | |
end | |
# usage in template (inside render) will be like this | |
<.live_component module={LiveWeb.Downvote} id={faq.id} faq={faq} faq_id={faq.id} /> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment