How to handle timeouts in liveview handle_event/3 callback?

In the form submit in LiveView, we usually do this callback:

def handle_event("save", params, socket) do
  ...saving process...
end

What is the right approach in handling the long saving process? Because if I wait inside the handle_event block, LiveView somehow refreshes the page (which I’m guessing because it restarts the process).

1 Like

Is saving process timing out? Or is it just taking a bit and the page is refreshing even though it succeeds?

@benwilson512 the saving process does not timeout. It actually just taking a bit then eventually succeeds. It’s just that the page refreshes. I’m guessing this is the condition when handle_event did not return anything at a specific time. Even something simple like:

def handle_event("save", _, socket) do
  Process.sleep(60_000)
  {:noreply, socket)
end

can replicate the issue.

Start separate process and do handling there waiting for message coming back with timeout.

@hauleth with that in mind, I was also thinking of using Task.start_link/1.

def handle_event("save", params, socket) do
  Task.start_link(fn ->
    ...saving process
    ...send message to liveview after save
  end)

  {:noreply, socket} 
end

Guess this will work. The only thing I worry about this approach is on the client side, class phx-submit-loading will be removed. Eventually enabling disabled elements with the phx-disabled-with attribute. Which means user can click the save again without knowing the previously submitted input are still on process.

I might hook another js to re-add that class again. Not sure if this is overall the right approach.

1 Like