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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews