Hi all,
I’m a bit confused about the role of handle_params in the LiveView life cycle. I’ve read https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-handle_params-3 many times and I still don’t understand it, hopefully someone can clarify.
Let me lay out what I understand from the docs:
-
mountis called twice, once on the initial HTTP request and again on the websocket connect. (BTW the docs read “once per LiveView life-cycle” which is quite confusing). -
handle_paramsis called aftermount, meaning it’s also called twice. - Both
mountandhandle_paramstake the same arguments and trigger a render.
The docs suggest we should load data in mount as it’s called once and mention handle_params is used to handle live_patch operations showing the following example:
def handle_params(params, _uri, socket) do
socket =
case params["sort_by"] do
sort_by when sort_by in ~w(name company) -> assign(socket, sort_by: sort)
_ -> socket
end
{:noreply, load_users(socket)}
end
load_users(socket) is not listed but it implies it’s a function that load the users from somewhere and sorts it using sort_by. Assuming we’re also loading data in mount wouldn’t that mean the loading is happening twice?
If handle_params is called regardless, takes the same arguments as mount, and is invoked on live_patch whereas mount is not, why not always load the content there instead of in mount?
Are we supposed to avoid loading if some elements are already present in the socket.assigns from mount?
It may be that I’m misunderstanding something but I’ve been confused about this for a while.
Thanks in advance!
the params that can change are loaded on handle_params.





















