To invoke a SignalR hub method from React, you can follow these steps:
npm install @microsoft/signalr
import { HubConnectionBuilder } from '@microsoft/signalr';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
connection: null
};
}
componentDidMount() {
const connection = new HubConnectionBuilder()
.withUrl('/myhub')
.build();
connection.start().then(() => {
console.log('SignalR connected');
// Save the connection instance to the component state
this.setState({ connection });
});
}
// ...
}
// Inside a class method or event handler
this.state.connection.invoke('SendMessage', message);
In this example, we assume that the SignalR hub has a method called "SendMessage" that takes a message parameter. You can replace "SendMessage" with the actual name of the hub method you want to invoke.
this.state.connection.invoke('SendMessage', message)
.then(response => {
// Handle the response from the hub method
})
.catch(error => {
console.error(error);
});
This example uses the Promise-based API for invoking hub methods, which allows you to handle both the response and any errors that may occur.
Asked: 2023-06-30 13:11:04 +0000
Seen: 15 times
Last updated: Jun 30 '23