An easy to use React hook for @microsoft/signalr
Please use Microsoft's Documentation and API Reference as guidance.
$ npm install use-signalr-hub @microsoft/signalr
$ yarn add use-signalr-hub @microsoft/signalr
import signalR from "use-signalr-hub"
const signalRHub = signalR.useHub("https://www.example.com/hub", {
onConnected: (hub) => {
// Connected to hub
hub.on("ReceiveMessage", (user, message) => {
// Listen to "ReceiveMessage" on hub
})
},
onDisconnected: (error) => {
// Disconnected from hub
},
onError: (error) => {
// Failed to connect to hub
}
})
const handleSubmit = (user, message) => {
signalRHub.invoke("SendMessage", user, message)
.catch((error) => {
// Failed to invoke "SendMessage" on hub
})
}
signalR.setDefaults({
httpTransportTypeOrOptions: {
accessTokenFactory: () => user.userData.token
},
automaticReconnect: false
})
const signalRHub = signalR.useHub(hubUrl, {
onConnected,
onDisconnected,
onReconnecting,
onReconnected,
onError,
enabled,
automaticReconnect,
httpTransportTypeOrOptions,
hubProtocol,
logging
})
onConnected?: (hub: HubConnection) => void
onDisconnected?: (error?: Error) => void
onReconnecting?: (error?: Error) => void
onReconnected?: (connectionId?: string) => void
onError?: (error?: Error) => void
enabled?: boolean
automaticReconnect?: number[] | IRetryPolicy | boolean
httpTransportTypeOrOptions?: IHttpConnectionOptions | HttpTransportType
hubProtocol?: IHubProtocol
logging?: LogLevel | string | ILogger
HubConnection | IRetryPolicy | IHttpConnectionOptions | HttpTransportType | IHubProtocol | LogLevel | ILogger
signalRHub: HubConnection | null