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
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 thingAnd 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
# functional component
def component(assigns) do
coffee_for_me = Coffee.get_coffee_for_me(assigns.id)
# ...some code here
end
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
attr(:coffee, Coffee, required: true)
def component(assigns) do
# ...you can use your coffee here
<p><%= coffee.title %><p>
end
- As much as possible, try to avoid database functions inside your functional components and make Liveview as the source of truth
Happy Coding
ย