Skip to content

Instantly share code, notes, and snippets.

@onedebos
Last active March 8, 2021 22:06
Show Gist options
  • Save onedebos/ff9713fee0213526214a4707c2fe7dc6 to your computer and use it in GitHub Desktop.
Save onedebos/ff9713fee0213526214a4707c2fe7dc6 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
import Pusher from "pusher-js";
import axios from "axios";
const Chat = ({ sender }) => {
const [chats, setChats] = useState([]);
const [messageToSend, setMessageToSend] = useState("");
useEffect(() => {
const pusher = new Pusher(process.env.NEXT_PUBLIC_KEY, {
cluster: "eu",
});
const channel = pusher.subscribe("chat");
channel.bind("chat-event", function (data) {
setChats((prevState) => [
...prevState,
{ sender: data.sender, message: data.message },
]);
});
return () => {
pusher.unsubscribe("chat");
};
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
await axios.post("/api/pusher", { message: messageToSend, sender });
};
return (
<>
<p>Hello, {sender}</p>
<div>
{chats.map((chat, id) => (
<>
<p>{chat.message}</p>
<small>{chat.sender}</small>
</>
))}
</div>
<form onSubmit={(e) => {handleSubmit(e)}}>
<input
type="text"
value={messageToSend}
onChange={(e) => setMessageToSend(e.target.value)}
placeholder="start typing...."
/>
<button
type="submit"
>
Send
</button>
</form>
</>
);
};
export default Chat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment