The beauty of assign_async/3
and async_result/1
# LiveView
def handle_params(params, _uri, socket) do
{:noreply,
socket
# ... more assigns here
|> assign_async_coffees()}
end
# ... more code here
defp assign_async_coffee(socket) do
assign_async(socket, :coffees, fn ->
{:ok, %{coffees: Coffee.load_more_coffees}}
end)
end
-
https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-async-operations
It allows the user to get a working UI quickly while the system fetches some data in the background or talks to an external service, without blocking the render or event handling
What I liked about the beauty of using
assign_async/3
is that everything is asynchronous. I get the chance to process data without blocking the render or event handling-
I also have the change to handle different states like the
loading
,failures
and thesuccessful result
You also want to catch any errors or exits and translate it to a meaningful update in the UI rather than crashing the user experience.
And just in case there will any exit errors, I will be able to handle that in the liveview.
The built-in component
# LiveView heex file
<.async_result :let={coffees} assign={@coffees}>
<:loading>Preparing what are the best coffees for you...</:loading>
<:failed :let={_failure}>Please be patient, something came up...</:failed>
<div :for={coffee <- coffees}>
Here is your coffee <%= coffee %>
</div>
</.async_result>
assign_async/3
has a partner that I could say abuilt-in
partner wherein you can use it to render the different states that you want to show to your users.You can even customize the
loading
andfailed
component slots to have an even more beautiful UI.
Users can choose nicely from the list of coffees from your application if you seamlessly implemented this kind of approach.
But I wonder does this one have any drawbacks?
That's another thing to find out.
Happy coding
Top comments (0)