defmodule SendItWeb.SubscriptionLive do
use SendItWeb, :live_view
alias SendIt.Marketing
@impl true
def mount(params, _session, socket) do
{:ok, assign_form(socket, params)}
end
@impl true
def render(assigns) do
~H"""
<.header>
Unsubscribe
<:subtitle>Enter your email address below to unsubscribe from all emails.
<.simple_form for={@form} id="subscription-form" phx-submit="save">
<.input type="email" field={@form[:email]} />
<:actions>
<.button phx-disable-with="Saving changes...">Unsubscribe
"""
end
@impl true
def handle_event("save", %{"email" => email}, socket) do
unsubscribe(socket, email)
end
defp unsubscribe(socket, email) do
case Marketing.unsubscribe(email) do
{:ok, _contact} ->
{:noreply,
socket
|> assign_form(%{})
|> put_flash(:info, "You have been unsubscribed from all emails.")}
{:error, reason} ->
{:noreply, put_flash(socket, :error, reason)}
end
end
defp assign_form(socket, params) do
email = handle_params(params)
assign(socket, :form, to_form(%{"email" => email}))
end
defp handle_params(%{"email" => email}), do: email
defp handle_params(_params), do: ""
end