Display an offline message in the phx-disconnected event

The setup (1.6.0-rc.0):

$ mix phx.new demo --no-ecto
$ cd demo
$ mkdir lib/demo_web/live

lib/demo_web/live/clock_live.ex

defmodule DemoWeb.ClockLive do
  use DemoWeb, :live_view

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

    {:ok, assign_current_time(socket)}
  end

  def render(assigns) do
    ~H"""
    <h1>UTC: <%= @now %></h1>
    """
  end

  def handle_info(:tick, socket) do
    Process.send_after(self(), :tick, 1000)

    {:noreply, assign_current_time(socket)}
  end

  defp assign_current_time(socket) do
    utc_now =
      Time.utc_now()
      |> Time.to_string()
      |> String.split(".")
      |> hd

    assign(socket, now: utc_now)
  end
end

Add live "/clock", ClockLive, :index in the router.

This displays a self updating clock on http://localhost:4000/clock

When I stop the server and restart it the clock will stop working for that pause and restarts automatically (which is very nice). But I’d like to display instead of @now the word offline during that offline phase.

Obviously I can’t solve this on the server because it is offline. How can I solve this with JavaScript on the client? My JavaScript knowledge is minimal and I have no idea if I can tackle this with Alpine.js or if I have to do JavaScript open heard surgery.

Let me rephrase: What is the cleanest way to display an offline message on the page?

A class is added to the live view container when disconnected: JavaScript interoperability — Phoenix LiveView v0.16.3

Have you tried this? Is it enough?

3 Likes

I haven’t. Thanks for pointing that out!

For everybody with the same problem: Here’s a GIF which shows the feature.

ScreenFlow