Handling live action

I am new to Phoenix_Live. I am going through Phoenix_Live project and need to handle live action in my code. Is handle_params the best place to handle the action? For example, I have :new action and have to change one of the assigns:

  def handle_params(_, _url, socket) when socket.assigns.live_action == :new do
    socket = assign(socket, selected_server: nil)
    {:noreply, socket}
  end

Assuming you want to access them on navigation via a patch link (<.link patch={~p"/foo/new"}>new</.link>) or a push_patch then yes, handle_params/3 is the place to do this as it is called whenever there is a patch event. From your example it looks like that is what you want. Otherwise, @live_action is available anywhere your assigns are. For example you could conditionally render a piece of your template in your render/1 callback based on the @live_action.

Just for completeness since you say you’re new, you can also write your code like this:

def handle_params(_, _url, %{assigns: %{live_action: :new}} = socket) do
  # ...

…which some people prefer, although I personally write it like you do so completely up to you :slight_smile:

PS: Welcome!

3 Likes