Refactor BreakingNewsLive

This commit is contained in:
Wout De Puysseleir 2023-03-14 18:11:53 -07:00
parent 185b1f84c0
commit a1d5ed9cbf
No known key found for this signature in database
GPG key ID: 3DE9371B50FEC46A

View file

@ -1,10 +1,12 @@
defmodule ExamplesWeb.BreakingNewsLive do
defmodule ExampleWeb.BreakingNewsLive do
use ExampleWeb, :live_view
@initial_news [
%{body: "World peace has been achieved!", id: 1},
%{body: "Some other crazy stuff happened", id: 2},
%{body: "Car crash in city center", id: 3}
%{id: 1, body: "Giant Pink Elephant Sighted Downtown"},
%{id: 2, body: "Local Cat Becomes Mayor of Small Town"},
%{id: 3, body: "Scientists Discover New Flavor of Ice Cream"},
%{id: 4, body: "World's Largest Pizza Baked in Local Pizzeria, Still Not Big Enough for Customers"},
%{id: 5, body: "Clown Epidemic Sweeps Through Town, Everyone Laughs Until They Realize the Clowns Aren't Joking"},
]
def render(assigns) do
@ -17,15 +19,14 @@ defmodule ExamplesWeb.BreakingNewsLive do
{:ok, assign(socket, :news, @initial_news)}
end
def handle_event("remove_news_item", %{"id" => id} = params, socket) do
socket = assign(socket, :news, Enum.reject(socket.assigns.news, fn item -> item.id == id end))
{:noreply, socket}
def handle_event("remove_news_item", %{"id" => id}, socket) do
updated_news = Enum.reject(socket.assigns.news, fn item -> item.id == id end)
{:noreply, assign(socket, :news, updated_news)}
end
def handle_event("add_news_item", %{"body" => item} = params, socket) do
new_item = %{body: item, id: get_id()}
{:noreply, assign(socket, :news, socket.assigns.news ++ [new_item])}
def handle_event("add_news_item", %{"body" => body}, socket) do
new_item = %{id: System.unique_integer([:positive]), body: body}
updated_news = socket.assigns.news ++ [new_item]
{:noreply, assign(socket, :news, updated_news)}
end
def get_id(), do: System.unique_integer([:positive])
end