DEV Community

Pau Riosa
Pau Riosa

Posted on

2

Things I Learned using Phoenix LiveView in 2024

Use handle_params/3 more often rather than mount/3 for assigning.

def mount(_params, _session, socket), do: {:ok, socket}
def handle_params(params, _uri, socket) do
   {:noreply,
        socket
        |> assign_here_1(params)
        |> assign_here_2(params)}
end
Enter fullscreen mode Exit fullscreen mode
  • Use pipelines, it adds more visibility and readability to keep track of what you have added and need more to add.

  • You can also do pattern matching at handle_params/3. So whenever you need to load or assign special use-cases depending on the parameters, that would be a great thing

  • And since you are using private functions to assign, you can reuse them whenever you want in different handle_params/3

LiveView as The Source of Truth

# LiveView module
def handle_params(params, _uri, socket) do
  {:noreply,
        socket
        |> assign_here_1(params)
        |> assign_here_2(params)}
end
Enter fullscreen mode Exit fullscreen mode
# functional component
def component(assigns) do
    coffee_for_me = Coffee.get_coffee_for_me(assigns.id)
    # ...some code here
end
Enter fullscreen mode Exit fullscreen mode
  • Try to create functional components that depends on assigns coming from the liveview.

  • So instead of doing the code above, try to create something like this

def handle_params(params, _uri, socket) do
  {:noreply,
        socket
        # ...more assign here
        |> assign_coffee(params)}
end

defp assign_coffee(socket, %{"coffee" => coffee} = _params} do
   coffee = Coffee.get_coffee(coffee)
   assign(socket, coffee: coffee)
end
Enter fullscreen mode Exit fullscreen mode
attr(:coffee, Coffee, required: true)
def component(assigns) do
    # ...you can use your coffee here
    <p><%= coffee.title %><p>
end
Enter fullscreen mode Exit fullscreen mode

As much as possible, try to avoid database functions inside your functional components and make Liveview as the source of truth

Happy Coding

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay