Skip to content

Instantly share code, notes, and snippets.

@berkslv
Created October 20, 2020 13:44
Show Gist options
  • Save berkslv/c73671fe739d21c8960310cdad9d6b12 to your computer and use it in GitHub Desktop.
Save berkslv/c73671fe739d21c8960310cdad9d6b12 to your computer and use it in GitHub Desktop.
Chat.js for SignlaR
import React, { useState, useEffect, useRef } from "react";
import { HubConnectionBuilder } from "@microsoft/signalr";
import ChatWindow from "./ChatWindow";
import ChatInput from "./ChatInput";
import { Container } from "reactstrap";
const Chat = () => {
const [connection, setConnection] = useState(null);
const [chat, setChat] = useState([]);
const latestChat = useRef(null);
latestChat.current = chat;
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl("http://localhost:5000/hubs/chat")
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
if (connection) {
connection
.start()
.then((result) => {
console.log("Connected!");
connection.on("ReceiveMessage", (message) => {
const updatedChat = [...latestChat.current];
updatedChat.push(message);
setChat(updatedChat);
});
})
.catch((e) => console.log("Connection failed: ", e));
}
}, [connection]);
const sendMessageToAll = async (user, message, userTo) => {
const chatMessage = {
user: user,
message: message,
to: userTo,
};
if (connection.connectionStarted) {
try {
await connection.invoke("SendMessageToUser", chatMessage);
} catch (e) {
console.log(e);
}
} else {
alert("No connection to server yet.");
}
};
return (
<div>
<Container className="mt-5">
<ChatInput sendMessageToAll={sendMessageToAll} />
<hr />
<ChatWindow chat={chat} />
</Container>
</div>
);
};
export default Chat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment