Search code examples
erlangelixirphoenix-frameworkalpine.jsphoenix-live-view

Socket rejoins again and again which causes Live View to emit events itself periodically. when using with Alpine js


Issue: Socket rejoins again and again which causes Live View to emit events itself periodically.

Scenario: I have index page which contains phx-change events. When I left the page idle for sometime, the events started to triggered automatically periodically. It is not limited to single page but it happen on each live view page, I googled the issue but couldn’t find any solution.

  • 1 reason I noticed that sometimes heartbeat stops for more than 1 minute(timeout limit is 1 minute), in this case socket rejoined again.

  • I increased timeout at client side as well at server side in Endpoint to check if this is the only issue but it didn’t work and socket behaved the same.

  • Did anyone face same issue before, what could be a possible reasons and how to avoid this issue, any suggestion?

Stack: PETAL

Elixir: 1.11 Erlang: 23.0 phoenix: 1.5.3 phoenix_live_view: 0.15.7 alpinejs “^2.8.2” Browsers: chrome, safari

I think issue is with Alpine Js but couldn’t figure out any solution.

Here is my app.js code

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
    uploaders: Uploaders,
    hooks: Hooks,
    params: { _csrf_token: csrfToken },
    timeout: 60000,
    dom: {
        onBeforeElUpdated(from, to) {
            if (from.__x) {
                Alpine.clone(from.__x, to);
            }
            flatpickr(".date-picker", {
                wrap: true,
                disableMobile: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
            flatpickr(".datetime-picker", {
                enableTime: true,
                wrap: true,
                disableMobile: true,
                "plugins": [new confirmDatePlugin({ confirmIcon: "", confirmText: "Confirm" })],
                time_24hr: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
        }
    }, 
    heartbeatIntervalMs: 10000
});

Endpoint Configuration:

 socket "/socket", PrintSimpleWeb.UserSocket,
  websocket: [
    timeout: :infinity,
  ],
    longpoll: false

  socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]

Solution

  • it was fixed by simple updating Elixir dependencies and npm packages. Here are the steps which I followed:

    > remove _build, node_modules, deps folder
    RUN: 
    > mix deps.get 
    > mix compile
    > npm install (inside /assets)
    > iex -S mix phx.server