Phx-click called too soon, handle_event not called

Trying to implement an infinite scroll using phoenix liveview and alpine js intersect.

Concept is, when the last element comes into the viewport, it triggers a button click. That button has a phx-click attribute. The backend obviously adds items at that point. Not sure it’s the best way to do it, but it works wonderfully most of the time.

Thing is, when the last item already is in the viewport on load, that button click seems to happen too fast. The alpine js intersect event gets triggered, but the click doesn’t reach the backend.

Is there a way to make sure the backend is ready to receive events before triggering the javascript event?

Basically, what you want is to know when the socket connection is established? If so, perhaps something like the ConnectionStatus hook explained here would help in this use case?

Hooks.ConnectionStatus = {
  mounted() {
    window.connected = true
  },
  disconnected() {
    window.connected = false
  },
  reconnected() {
    window.connected = true
  }
}

then, in the logic where you trigger the button click:

if (connected) {
// trigger button click
} else {
// set a timeout to re-try?
}

Also, see this infinite scrolling example from the docs as an alternative option pushing events from the client to the server through pushEvent and pushEventTo methods.

1 Like