Browse Source

fix: add with_user function for live views

main
Inhji Y. 8 months ago
parent
commit
7d3a59bce8
  1. 3
      lib/mirage/accounts.ex
  2. 4
      lib/mirage_web/live/link_live/show.ex
  3. 7
      lib/mirage_web/live/live_helpers.ex
  4. 4
      lib/mirage_web/live/note_live/index.ex
  5. 6
      lib/mirage_web/live/note_live/show.ex

3
lib/mirage/accounts.ex

@ -59,6 +59,9 @@ defmodule Mirage.Accounts do
"""
def get_user!(id), do: Repo.get!(User, id)
def get_user(nil), do: nil
def get_user(id), do: Repo.get(User, id)
@doc """
Returns true if a user has been created, false otherwise.

4
lib/mirage_web/live/link_live/show.ex

@ -4,8 +4,8 @@ defmodule MirageWeb.LinkLive.Show do
alias Mirage.Links
@impl true
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, socket |> assign(:current_user, Mirage.Accounts.get_user!(user_id))}
def mount(_params, session, socket) do
{:ok, socket |> with_user(session)}
end
@impl true

7
lib/mirage_web/live/live_helpers.ex

@ -1,5 +1,6 @@
defmodule MirageWeb.LiveHelpers do
import Phoenix.LiveView.Helpers
import Phoenix.LiveView, only: [assign: 3]
@doc """
Renders a component inside the `MirageWeb.ModalComponent` component.
@ -21,4 +22,10 @@ defmodule MirageWeb.LiveHelpers do
live_component(socket, MirageWeb.ModalComponent, modal_opts)
end
def with_user(socket, %{"user_id" => user_id} = _session) do
socket |> assign(:current_user, Mirage.Accounts.get_user(user_id))
end
def with_user(socket, _), do: socket |> assign(:current_user, nil)
end

4
lib/mirage_web/live/note_live/index.ex

@ -5,11 +5,11 @@ defmodule MirageWeb.NoteLive.Index do
alias Mirage.Notes.Note
@impl true
def mount(_params, %{"user_id" => user_id}, socket) do
def mount(_params, session, socket) do
{:ok,
socket
|> assign(:notes, list_notes())
|> assign(:current_user, Mirage.Accounts.get_user!(user_id))}
|> with_user(session)}
end
@impl true

6
lib/mirage_web/live/note_live/show.ex

@ -9,10 +9,8 @@ defmodule MirageWeb.NoteLive.Show do
defp page_title(:edit, note), do: "[Edit] #{note.title}"
@impl true
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok,
socket
|> assign(:current_user, Mirage.Accounts.get_user!(user_id))}
def mount(_params, session, socket) do
{:ok, socket |> with_user(session)}
end
@impl true

Loading…
Cancel
Save