I'm a huge fan of the popular Discord App. Diskord is my take on cloning the real deal. Gamers (or anyone really) can sign up, login, create guilds (with optional guild emblems), create guild channels, and chat (with optionally attached images/gifs) with guild members all in real time.
Diskord was built using React, Redux, Ruby on Rails, ActionCable, Active Storage, PostgreSQL, and AWS S3
I wanted to keep my React presentational component as readable and simple as possible, so I chose to compose a function and pass it down with dispatch to that same presentational component. Code related to implementing action cable is shown below.
Helper methods to send data, and subscribe to a specific channel from messages controller
class ChatChannel < ApplicationCable::Channel
def self.send_data(channel_name, data)
ActionCable.server.broadcast(channel_name, data)
end
def subscribed
stream_from specific_channel
end
private
def specific_channel
"chat_#{params[:channelId]}"
end
end
class Api::MessagesController < ApplicationController
def create
@message = Message.new(message_params)
if @message.save
ChatChannel.send_data("chat_#{@message.channel_id}", message_payload.as_json)
render :show
end
end
end
import { receiveMessage } from "../../actions/message_actions";
let subscription
function subscribeToChannel(channelId, dispatch) {
if (subscription) {
subscription = subscription.unsubscribe();
}
subscription = App.cable.subscriptions.create(
{ channel: "ChatChannel", channelId: channelId },
{
received: data => {
dispatch(receiveMessage(data));
}
}
);
}
const mapDispatchToProps = dispatch => {
const subscribe = channelId => subscribeToChannel(channelId, dispatch);
return {
subscribe,
};
};
componentDidMount() {
this.props.fetchMessages(this.props.channelId);
if (Number.isInteger(this.props.channelId)) {
this.props.subscribe(this.props.channelId);
}
}
componentDidUpdate(previousProps) {
if (previousProps.channelId !== this.props.channelId) {
this.props.fetchMessages(this.props.channelId);
this.props.subscribe(this.props.channelId);
}
if (previousProps.messages.length !== this.props.messages.length) {
this.messagesIndex.current.scrollIntoView();
}
}