Skip to content

Instantly share code, notes, and snippets.

@thisisjofrank
Created August 7, 2020 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thisisjofrank/f046c148b9aac2ff3afe6463e2bf3a31 to your computer and use it in GitHub Desktop.
Save thisisjofrank/f046c148b9aac2ff3afe6463e2bf3a31 to your computer and use it in GitHub Desktop.
A functional component built with React that uses Ably
import React, { useState, useEffect } from 'react';
import Ably from "ably/promises";
const client = new Ably.Realtime("you-api-key-here");
const Component = (props) => {
const channel = client.channels.get('some-channel');
const [ messages, updateMessages ] = useState([]);
useEffect(() => {
async function subscribe() {
await channel.subscribe(message => {
console.log("A message was received", message);
const newMessages = messages.slice();
newMessages.push(message.data.text);
updateMessages(newMessages);
});
}
subscribe();
return function cleanup() {
channel.unsubscribe();
};
});
const sendMessage = () => {
channel.publish({ name: "myEventName", data: { text: "Some random stuff here." } });
};
return (
<main>
<button onClick={ (e) => sendMessage(e) }>Click here to send a message</button>
<h2>Messages will go here:</h2>
<ul>
{ messages.map((text, index) => (<li key={"item" + index}>{text}</li>)) }
</ul>
</main>
)
};
export default Component;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment