ruby - React with Rails REST api - actioncable -
i have react frontend(not using react-rails gem) , want use rails api realtime interaction. have post.coffee code in rails working actioncable:
app.post = app.cable.subscriptions.create "postchannel", connected: -> disconnected: -> received: (data) -> console.log(data) document.getelementbyid('test').innerhtml = data['message'] notify: (message) -> @perform 'notify', message: message and post_channel.rb
class postchannel < applicationcable::channel def subscribed stream_from "post_channel" end def unsubscribed # cleanup needed when channel unsubscribed end def notify(data) actioncable.server.broadcast 'post_channel', message: data['message'] end end working example:
now in react app, lets on page load [ componentwillmount() ], want 'call' notify method post_channel.rb. how it? have searched method , saw post's accepted answer: how use actioncable api
so in react app's componentwillmount() lifecycle, have code:
componentwillmount() { var cable = actioncable.createconsumer('ws://localhost:8000/cable'); cable.server.broadcast 'post_channel', { message: 'ji'} } the code in componentwillmount not call websocket in rails app. how this? dont see resource. or recommend websocket library best react-rails stack?
solution
should similar rails .coffee code
componentwillmount() { var cable = actioncable.createconsumer('ws://localhost:8000/cable'); var subscription = cable.subscriptions.create('postchannel', { connected: function() { // calls `notify` method in `post_channel` once subscription has connected this.notify({ message: 'ji'}); // seems me `notify` code above once-off action , won't using subscription anymore; // if that's case then, uncomment line below unsubscribe after performing `notify` above // this.unsubscribe(); }, received: function(data) { // there new message; here... console.log(data.message); }, notify: function(message) { this.perform('notify', message: message) } } ) } recommendation
you'd ought have 1
consumerobject (useactioncable.createconsumer('ws://localhost:8000/cable');once), , make global in app speed things (and less code), because you'll have 1 websocket endpoint anyway (the rails server), unless of course have different multiple websocket urls (on different rails servers or apps?). might want makesubscriptionvariable above global, can.notify(...)anywhere want, , not instantiating subscription each time.i built gem live_record syncs records js-client. though not intentionally support pushing "messages" rails server, in case might find useful, feel free try out! :)


Comments
Post a Comment