Softknobs

Softknobs

Problem handling a timeout in a LiveComponent

Hi,

I have a stateful LiveComponent where I would like to handle a timeout. This timeout should occur a few seconds after one of the handle_event functions is no longer being called.
I already did this in a LiveView and it was super easy: I call Process.send_after and do the work in the matching handle_info that is called with socket as a parameter.

In a LiveComponent, handle_info does not exist. Handling this in the parent LiveView won’t work because I need to alter the socket from the component but the socket passed to handle_infois the parent LiveView’s socket.

In every scenario I tried I end up with the following problem: at one point I need to update the socket after the delay, so I do something like this:

def start_timeout(socket) do
Process.sleep(2000)
<send event with the socket with whatever tool>
end

The problem with this approach is that there is no garantee that the socket was not altered during the sleep time. And I really have no idea, with my actual knowledge of Elixir and Phoenix, how to handle this case.

Any clues on how this can be done at the LiveComponent’s level? At this point the only solution I see is to migrate the LiveComponent’s code in the LiveView and use handle_info from there. I know this is not the best solution as I would loose the modularity and end up with monolithic Liveviews. But I am just not ready to dig in LiveViews code to fully understand the inner logic.

Thank you.

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

FYI:

       spawn fn ->
         IO.puts("====================== sleep start")
        Process.sleep(5000)
         IO.puts("====================== sleep over")
         \< update socket state here \>
       end

The whole \< update socket state here \> bit was never going to work, even if did all of this in the parent live view. You can send the live view a message and have it update the socket there, but the socket is immutable, and can’t be changed in another process at all.

Perhaps a relatively simple solution could look like this:

live_component(YourComponent, %{
... other assigns
done: @done_components[id-of-component]
})
  # in your livesocket
  def update(params, socket) do
     # The parent live view is telling this live component that it has timed out, react accordingly.
     if params.done do
     end
  end

  def handle_event("patch_received", patch, socket) do
    socket = assign(socket, :import, %{socket.assigns.import | count: socket.assigns.import.count + 1})
    socket = reset_timer(socket)
    {:noreply, socket}
  end

  defp timer(socket) do
    Process.cancel_timer(socket.assigns.timer_ref)
    # clear out the timeout. This is important because technically the timer could have fired 
    # right as we canceled it.
    id = socket.assigns.id
    receive do
      {:timeout, ^id} -> :ok
    after
      0 -> :ok
    end
    # Send ourselves a message in 5 seconds with the id of the live socket
    Process.send_after(self, {:timeout, socket.assigns.id}, 5_000)
  end

Then in the live view we just need to handle the message and set the done flag properly:

# in the live view
# you also need to initialize :done_components on mount to `%{}`
def handle_info({:timeout, component_id}, socket) do
  socket = update(socket, :done_components, fn done_components ->
    Map.put(done_components, component_id, true)
  end)
  {:noreply, socket}
end

Basically, the idea is this. The live component manages the timeout timer, canceling it and restarting it if you get a payload. If the timeout timer is allowed to fire it sends a message to the actual live view, which essentially “routes” that fact to the live component via the params to the live component.

Also Liked

Softknobs

Softknobs

Yes, that’s it! I knew my solution did not work because of immutability but just could not find how to communicate to the component from the parent. I had not realized update could be used for this in this case, this was the missing link I was looking for, thank you!

I also like the use you make of the id, I will probably reuse this idea.
Thank you.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement