msantoli
Assign_async misbehaving with multiple live_views
We are developing a phoenix application where we have a dashbaord with multiple widgets.
Each widdget is a liveview and they are rendered at runtime in the main liveview page:
<%= live_render(
@socket,
module_name,
id: dashboard_widget.id,
session: %{
some_params
}
) %>
In some of these widgets we have assign_async to lazy load data.
If we have only 1 widget in the dashbaord everything is working perfectly.
If we had more thatn 1 widget with assign_asyncs inside, it can happens that on one of the widgets the asyng variable is not updated correctly, we always have the loading state set to true.
Putting IO.inspect to tdebug the async_task is working properly and returns without errors, it looks like it is the liveview variables that don’t get updated.
Thanks
Massimo
Most Liked
gushonorato
It’s hard to help without seeing the code from the parent and child LiveViews, but I have a question: is there any good reason to use LiveViews for implementing the widgets instead of a LiveComponent?
gushonorato
It looks like you’re running into some race conditions with your LiveView updates. I think the issue is that push_state is happening before the ui_state is ready. Try splitting the logic for updating the socket and calling push_event into two separate functions. For example:
def handle_async(:load_ui_data, {:ok, fetched_data}, socket) do
%{ui_data: ui_data} = socket.assigns
ui_data = AsyncResult.ok(ui_data, fetched_data)
socket = assign(socket, :ui_data, ui_data)
send(self(), :update_timer)
{:noreply, socket}
end
I get why you’re nesting LiveViews, but if it were up to me, I’d go with a LiveView + LiveComponent setup and a central broker. By consolidating state updates in a single place, you can more effectively manage transitions and reduce the chance of race conditions. Furthermore, using fewer LiveViews and more LiveComponents with a central broker reduces the number of processes the application needs to open, which lowers resource consumption and ensures better scalability as the application grows.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









