Reactjs, pass HubConnectopmBuilder to toher components

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

props are passed as properties on the props object.

export default function Parent() {
  return (
    <div className="App">
      <Child someProp="somePropValue"/>
    </div>
  );
}

function Child(props) {  
  return (
    <div className="App">
      {props.someProp}
    </div>
  );
}

Or using destructuring to get the property from the props object.

function Child({someProp}) {  
  return (
    <div className="App">
      {someProp}
    </div>
  );
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.