elixirphoenix-frameworkphoenix-live-view

How to stop page refresh in a Liveview template


My LiveView app sets some initial states (e.g, button_label) in the mountfunction. The template appears to be re-mounted as it goes through some message passing.

In the following example, the button label is initially set to "Click to run", and when the button is clicked, it successfully changes to "Running..." and then "Still in progrss". However, mount is automatically run again, and the label goes back to "Click to run". The desired behavior is that the label stays as "Still in progress" until another message is received indicating the process is completed later in the process.

What triggers the re-mounting, and how can I stop that?

def mount(_params, _session, socket) do
   {:ok, assign(socket, button_label: "Click to run")}

def handle_event("run_process", value, socket) do
    live_view = self()

    Task.start(fn ->
      result = "Some tasks to run here"  
      send(live_view, {:in_progress, result})
    end)

    {:noreply, assign(socket, button_label: "Running..")}

def handle_info({:in_progress, result}, socket) do
    IO.inspect("result", label: "in_progress ++")
    {:noreply, assign(socket, button_label: "Still in progress")}
end


[Leex]
<button phx-click="run_process"><%= @button_label %> </button>

Solution

  • @schrockwell at the Elixir slack channel kindly provided this answer. It solved my problem.

    Try adding the type="button" attribute to the tag

    That will prevent the form from trying to be submitted on the button click.

    [Leex]
    <button type="button" phx-click="run_process"><%= @button_label %> </button>