Created
August 7, 2020 10:35
-
-
Save thisisjofrank/f046c148b9aac2ff3afe6463e2bf3a31 to your computer and use it in GitHub Desktop.
A functional component built with React that uses Ably
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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