I Know how to make a Hub Connection with Signalr using the “@microsoft/signalr” library for reactjs
function App() {
const[Newconnection, setNewConnection] = useState(null);
const Connection = new HubConnectionBuilder()
.withUrl('https://localhost:44332/chatHub')
.withAutomaticReconnect()
.build();
useEffect(() => {
(async() =>{
await Connection.start().then(setNewConnection(Connection)).then(console.log("Hub Connected"))
})()
}, []);
how can re-use the Connection so i can pass it on to another component without constantly re-building te Connection.
I have tried something like this:
const[Newconnection, setNewConnection] = useState(null);
const Connection = new HubConnectionBuilder()
.withUrl('https://localhost:44332/chatHub')
.withAutomaticReconnect()
.build();
useEffect(() => {
(async() =>{
await Connection.start().then(setNewConnection(Connection)).then(console.log("Hub Connected"))
})()
}, []);
<Router>
<Switch>
<Route exact path="/LiveChat">
<LiveChat Connection={Newconnection}/>
</Route>
</Switch>
</Router
the LiveChat component:
const LiveChat = (Connection) => {
const send = () => {
console.log("Message is send")
Connection.invoke("SendAll",text)
}
return (<div>
<h2>Talk with one of our employees</h2>
<div className="ChatArea">
</div>
<textarea onChange={(e) => setText(e.target.value)}/>
<button onClick={send}>Send Text</button>
</div> );
}
}
Once i press the “send” function it says:
TypeError: Connection.invoke is not a function