Skip to content

Instantly share code, notes, and snippets.

@thisisjofrank
Last active August 7, 2020 09:29
Show Gist options
  • Save thisisjofrank/58888b6514430fd37389eeff8e35b9eb to your computer and use it in GitHub Desktop.
Save thisisjofrank/58888b6514430fd37389eeff8e35b9eb to your computer and use it in GitHub Desktop.
An example of a react component that uses Ably to publish to and subscribe to a channel
import React from 'react'
import Ably from "ably/promises";
const client = new Ably.Realtime("your-ably-api-key");
export default class AblyMessageComponent extends React.Component {
constructor() {
super();
this.state = { messages: [] };
}
async componentDidMount() {
this.channel = await client.channels.get("my-cool-channel");
await this.channel.subscribe(message => {
console.log("A message was received", message);
this.state.messages.push(message.data.text);
this.setState({ messages: this.state.messages });
});
console.log("You are subscribed");
}
async componentWillUnmount() {
this.channel.unsubscribe();
console.log("You are unsubscribed");
}
sendMessage() {
this.channel.publish({ name: "myEventName", data: { text: "Some random stuff here." } })
}
render() {
return (
<main>
<button onClick={ (e) => this.sendMessage(e) }>Click here to send a message</button>
<h2>Messages will appear here:</h2>
<ul>
{this.state.messages.map((text, index) => (<li key={"item" + index}>{text}</li>))}
</ul>
</main>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment