简体   繁体   中英

Best way to update state using Rails actioncable in ReactJS

Forgive me if this is ramble-y, I'm pretty comfortable with Rails, but React is still pretty new to me.

I've got a new Rails 6 app using ActionCable and Webpack for the ReactJS front end all contained within the app. This installation seems to have taken care of a lot of the work connecting ActionCable to ReactJS using the @rails/actioncable npm package. All the tutorials I've read seem to be using Rails 5 which i think required more setup to get things going. I've generated a GardensChannel which created the following files.

On the Rails side

class GardensChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'gardens_channel'
  end

  def received(data)

  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

On the ReactJS side

import consumer from "./consumer"

consumer.subscriptions.create("GardensChannel", {
  connected() {
    console.log ('Im connected!')
    // Called when the subscription is ready for use on the server
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    console.log(data)
  }
});

Just with that and no other configuration I can run ActionCable.server.broadcast 'gardens_channel', "TEST!" and see TEST! pop up in my Devtools Console.

What I'm hoping to do is hook up the received data to update my apps state using the useContext hook which I have already configured with a reducer and such.

Actioncable/ReactJS tutorials I have read all seem to assume two things. That I'm using Redux (I'm trying to avoid it since it seems overkill) and that I need the react-actioncable-provider npm package, but it seems like that functionality is already take care of since I'm already successfully connected to the channel and receiving data. So the rest of those tutorials are unhelpful.

You can view the codebase here . What is the best way to take the data I'm receiving from the channel and pass it to my useContext hook?

What I would do is,

import consumer from "./consumer";

const GardensChannel = updateReceivedData => {

  return consumer.subscriptions.create("GardensChannel", {
    connected() {
      console.log ('Im connected!')
      // Called when the subscription is ready for use on the server
    },

    disconnected() {
      // Called when the subscription has been terminated by the server
    },

    received(data) {
      updateReceivedData(data);
    }
  }
}

And then you can update the context with the use of updateReceivedData .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM