xxdavid

xxdavid

Hi!

I’ve watched Jose’s video about optimistic updates in LiveView and read the relevant docs, and it all sounds great. However, I still don’t get how are we supposed to handle situations that end with a failure.

For example, suppose I have a list of rows (similarly as in the video), and each row has a delete button. If a user presses the delete button, I would like to immediately show some feedback. To do that, I can either optimistically hide the row (JS.push("delete") |> JS.hide(to: "the-row-selector")) or change its appearance (e.g., JS.push("delete") |> JS.add_class("opacity-50", to: "the-row-selector")). This works well. If the server then deletes the row successfully, the deletion of the DOM node is sent to the client and the client removes it from the DOM which nicely agrees with the optimistic update.

But if the deletion on the server fails (for whatever reason), I think we should revert the optimistic update (i.e., show the element again or remove the opacity-50 class). But LiveView does seem to work that way. In case the handle_event corresponding to the deletion event does not alter assigns in a way that deletes the row, the optimistic update on the client side is kept unchanged.

I’ve read the docs multiple times and I still don’t understand what is the recommended solution to this problem. I think that reverts in case of failure are inseparable from optimistic updates so I am probably missing something… How do you handle these situations?

Showing Posts 1 to 10

rhcarvalho

rhcarvalho

You have a few options, one of them sending a JS command from the server to remove the class.

If you want to pull the add/remove class commands together in the source code you could write two defp, one for the delete and another for the “undelete” action.

Another option is assume failure to delete is unlikely and “let it crash” and let LiveView restore the state from the database.

krasenyp

krasenyp

I’d add a piece of presentation-related metadata to each item. For example a deleting? field. This way when you decide to delete a row, you do the following in your LiveView code and use the deleting? field in your template to determine what styling and logic to apply:

def handle_event("delete", %{"id" => "my_stream_" <> id}, socket) do
  item = MyApp.get_item!(id)

  socket = 
    socket
    |> stream_insert(:items, %{item | deleting?: true})
    |> start_async({:delete_item, item}, fn -> MyApp.delete_item!(item) end)

  {:noreply, socket}
end

def handle_async({:delete_item, item}, {:ok, _}, socket) do
  {:noreply, stream_delete(socket, :items, item)}
end

def handle_async({:delete_item, item}, {:exit, %Ecto.NoResultsError{}}, socket) do
  {:noreply, stream_delete(socket, :items, item)}
end

def handle_async({:delete_item, item}, {:exit, _reason}, socket) do
  {:noreply, stream_insert(socket, :items, %{item | deleting?: false})}
end

I haven’t tested the above code but it should be more or less what you need. This “pattern” is generally useful but it’s not the first thing people reach for because they’re taught that data should go straight from the database to the view which is inflexible and most of the times leads to awful code.

cmo

cmo

Isn’t that pessimistic though?

krasenyp

krasenyp

Nope. You update the UI before the actual deletion takes place. Look the stream_insert again.

josevalim

josevalim

Creator of Elixir

Exactly. Because the server is the source of truth, you can always “undo” the client. The default approach is that a crash will force the whole view to be reloaded, but outside of that, you could send a JS command that undoes it (as @rhcarvalho mentioned), resend the whole stream, etc.

cmo

cmo

Depends how you define optimistic. You have a trip to the server, which can be pretty slow for some people, before you update the UI. One would assume the delete is going to be a lot quicker than a server round trip.

xxdavid

xxdavid OP

Thank you all for your replies!

I am dealing with a situation where the failure is not that unlikely so I would like to avoid crashing the LiveView.

@rhcarvalho and @josevalim, you both have mentioned sending a JS command from the server. What do you mean by that? Sending an event (using push_event) and executing a JS command on some element (using execJS) in a hook that listens for the event?

tfwright

tfwright

If you are pessimistic about the update shouldn’t the UX reflect that? IMO the whole point of optimistic updates is that since failure is so unlikely, it can be treated as exceptional. If it’s not unlikely, I would argue a better design would not hide that from your users but make it clear/graceful (nice, unobtrusive loading/error states)

xxdavid

xxdavid OP

That’s a good point. In case of an error, I would like to show an error flash for sure. However, I think that during the action, lowering the opacity of the row may be a good way to give the user some immediate feedback that something is happening, even if the action might eventually fail (reverting the opacity and showing the flash in that case). What do you think?

cmo

cmo

If it’s likely to fail, keeping it there but doing that, adding a “deleting…” or something or rather to indicate what is going on is worth it.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews