简体   繁体   中英

How to stop page refresh in a Liveview template

My LiveView app sets some initial states (eg, button_label) in the mount function. 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>

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM