Jason O.
Jason O.

Reputation: 3310

In Phoenix Liveview, how to change button labels to indicate job status

Does LiveView update DOM when a value is added to assigns like assign(socket, strLabel: "Push me")? or when handle_event returns { .. , socket}? I have a button which reads from a DB when clicked. I want the button label to be changed to "Reading..." while the DB reading occurs. Below is my attempt, but the temporary label "Reading.." never appears.

 def handle_event("button_click", value, socket) do

    socket1 = assign(socket, btnLabel: "Reading..")   ##temporarily change the button label

    {:ok, data} = log_list(10000, list_name)     

    socket1 = assign(socket, btnLabel: "Press me")   ## restore original button label

    {:noreply, socket1}
  end

Upvotes: 1

Views: 593

Answers (1)

Jason O.
Jason O.

Reputation: 3310

(Here is a response from @schrockwell from the Elixir Liveview Slack channel.)

What you need to do is have an assign that tracks that “reading” state, like a simple boolean, and is assigned immediately in the handle_event , and then spawn some process (e.g. a Task) that does the DB lookup and sends a message back to the LiveView process when the lookup completes

def handle_event("some_event", params, socket) do
   live_view = self()
   Task.start(fn ->
      result = do_the_db_lookup_here()
      send(live_view, {:db_result, result})
   end)
   {:noreply, assign(socket, busy: true)}
end

def handle_info({:db_result, result}, socket) do
  {:noreply, assign(socket, result: result, busy: false)}
end

Upvotes: 1

Related Questions