Send JavaScript variables from client to server

I think pushing on mount will work if you’re doing it during the second connected mount, not the first one.
So when connected?(socket) returns true

But I’m not 100% sure :grimacing:

That is more likely to work that’s true, but still not really a guarantee, because all that connected? on its own guarantees is that liveview’s JS has run, it doesn’t guarantee that the event specific listeners have been set up.

EDIT: That said, it’s very likely they’ve been set up, so that could work. I still think hooks are a pretty low boiler plate, hard to get wrong answer here though.

I’m not saying it was the correct way to do it but pushing the event on mount after connected?(socket) was causing it fire when I was testing it yesterday because I saw the data I logged in the console from the handler.

There was nothing in here about using hooks when they are not binded to elements. If you do not add a phx-hook attribute to an element, then mounted() inside the hook is treated as when the whole document is mounted? Do you still need to use push_event() on the server in order for it to fire?

I basically want the hook to fire onload

I’m confused. Can you explain what is triggering this event? Up until now I thought that the sequence of events was:

  1. something happens on the server
  2. server reacts and send something to the client
  3. client gets the message from the server and has to reply

I basically want the hook to fire onload

if you want something to fire “onload” in a hook your best bet is to put the logic in the mounted callback. That fires when the LV is mounted. You have of course access to the window object from the hook so you can do your media queries or what not from there.

No, this was something I wanted firing onmount/onload (not sure what the proper terminology is in this case here), so that is why was adding push_event() within def mount() on the server. It’s because I need to know the viewport size right away, not upon any specific event (other than the event of the page loading/all components mounting).

So with that in mind, adding push_event on the server in def mount() after connected?(socket) would be ok here? No phx-hook attribute is needed right?

Add a js hook, and put the logic in the mounted callback of the hook. From there you get the viewport information and push it to the server. mounted callback is executed on the client after the LV has completed mounting.

That’s what I figured, thank you again everyone for all of your help