cboe
cboe

Reputation: 477

Rails Actioncable success callback

I use the perform javascript call to perform an action on the server, like this:

subscription.perform('action', {...});

However, from what I've seen there seems to be no builtin javascript "success" callback, i.e. to let me know the action is concluded on the server's side (or possibly failed). I was thinking about sending a broadcast at the end of the action like so:

def action(data)
  ...do_stuff
  ActionCable.server.broadcast "room", success_message...
end

But all clients subscribed to this "room" would receive that message, possibly resulting in false positives. In addition, from what I've heard, message order isn't guaranteed, so a previous broadcast inside this action could be delivered after the success message, possibly leading to further issues.

Any ideas on this or am I missing something completely?

Upvotes: 2

Views: 1314

Answers (2)

Hugo Hernani
Hugo Hernani

Reputation: 165

Maybe what you are looking for is the trasmit method: https://api.rubyonrails.org/v6.1.3/classes/ActionCable/Channel/Base.html#method-i-transmit

It sends a message to the current connection being handled for a channel.

Upvotes: 0

hansottowirtz
hansottowirtz

Reputation: 692

Looking at https://github.com/xtian/action-cable-js/blob/master/dist/cable.js and , https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#send(), perform just executes WebSocket.send() and returns true or false, and there is no way to know whether your data has arrived. (That is just not possible with WebSockets, it seems.)

You could try using just a http call (I recommend setting up an api with jbuilder), or indeed broadcasting back a success message.

You can solve the order of the messages by creating a timestamp on the server, and sending it along with the message, and then sorting the messages with Javascript.

Good luck!

Upvotes: 4

Related Questions