Receiving Commands with ActionCable

Let’s use ActionCable to deal with multiple attempts on the same ticket page by different browsers.

ActionCable broadcast

The interactions work now, but we still need to catch the ActionCable broadcast if another browser on the same page holds a ticket. The tricky part here is that the display depends on a piece of client-side state, the “tickets to buy count” number, that the server won’t know when it makes the broadcast.

There are the three ways to make this work:

  • We could make the “tickets to buy count” number server-side state by having the server store it in a session or something similar and broadcast that information to other browsers via ActionCable when it changes. This would not be clear to the user.

  • We could have the ActionCable broadcast send versions of the seat grid with all possible tickets to buy numbers and have the receiver pick the correct one for display. It might be a good choice in another context, but the possible amount of extra data being sent is too high in this case.

  • We can have the ActionCable broadcast be received as a signal for the client to call the server and request the seat grid with the correct ticket to buy number. There’s an extra server call here but, overall, this is the easiest solution to manage.

The last version works for us because the request the client would make is the same request we’re already making when the pull-down menu changes. This is why we added the subtotal call to the form response.

Stimulus Controller

We’ve already set this up in the markup. The pull-down form declares a Stimulus controller called cable-receiver that also declares the form element as a target. Here’s the code for that Stimulus controller:

Get hands-on with 1200+ tech skills courses.