Last active
March 8, 2021 22:06
-
-
Save onedebos/ff9713fee0213526214a4707c2fe7dc6 to your computer and use it in GitHub Desktop.
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 { 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