r4z4

r4z4

Request: LiveView Timer Example

Hello

I am struggling to implement a simple timer in LiveView, and so I was wondering if anyone knew of any good examples out there that I could take a look at? I just want to display a simple countdown timer on the page, and have access to those values (the count). Thanks :slight_smile:

Marked As Solved

zachallaun

zachallaun

This is a LiveComponent, not a LiveView, which means its rendered “embedded” is another process – not as its own process. If you stick a handle_info in the module that renders this, does a message come through?

Also Liked

zachallaun

zachallaun

Awesome!

I’d recommend this section of the docs. Also, at the risk of going too far, I think you’re doing yourself a disservice by using Surface while you’re getting started with and familiar with LiveView. I think Surface is awesome, but especially with LiveView 0.18+, much of the gap has been closed, and it will be much easier to find solutions/understand what’s going on if you don’t have to look in two places.

For instance, I think the Surface automatically delegates handle_event to live components, e.g.

# When using Surface
use Surface.LiveComponent

def render(assigns) do
  ~F"""
  <button :on-click="some_event">Button</button>
  """
end

def handle_event("some_event", _, socket) do
  ...
end

# When using LiveView
use Phoenix.LiveComponent

def render(assigns) do
  ~H"""
  <button phx-click="some_event" phx-target={@myself}>Button</button>
  """
end

def handle_event("some_event", _, socket) do
  ...
end

Notice that in the Phoenix.LiveComponent version, you have to explicitly target @myself for the event to go to the live component and not the parent live view. I believe Surface does that delegation automatically, but it obviously can’t delegate send(self(), ...) because it doesn’t have that level of control.

samc

samc

I’m not sure about other examples out there but here is how I would approach just a simple countdown using erlang’s :timer

defmodule MyAppWeb.ExampleLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    if connected?(socket), do: :timer.send_interval(1000, self(), :tick)

    {:ok, assign(socket, %{count: 60})}
  end

  def handle_info(:tick, socket) do
    {:noreply, assign(socket, count: socket.assigns.count - 1)}
  end

  def render(assigns) do
    ~H"""
    <div><%= @count %></div>
    """
  end
end

Calling :timer.send_interval will send a message to the liveview process (i.e. itself) that can then be handled to decrement the current count. The count variable will be available in socket.assigns.count to use elsewhere or to add some logic when the timer reaches zero etc.

Sebb

Sebb

this minimal example works for me, ie getting these warnings of unhandled msgs and responding to GET with “test”.

debug] warning: undefined handle_info in ToolPocWeb.ToolLive. Unhandled message: :tick 
defmodule TestWeb.TestLive do
  use TestWeb, :live_view

  def mount(_, _, socket) do
    if connected?(socket), do: :timer.send_interval(1000, self(), :tick)
    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    test
    """
  end
end

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
vegabook
I'm brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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 fore...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52238 488
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, "eq...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35953 110
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement