-
Notifications
You must be signed in to change notification settings - Fork 143
feat: add SignalR reconnect provider #5153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
IvanIlyichev
merged 3 commits into
shesha-io:main
from
MishaliaPillay:mishalia/feat/reconnect-signalR-main
Aug 19, 2026
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| import * as signalR from '@microsoft/signalr'; | ||
|
|
||
| import React, { PropsWithChildren, useContext, useEffect, useReducer, useRef } from 'react'; | ||
| import { getFlagSetters } from '../utils/flagsSetters'; | ||
| import { | ||
| ISignalRConnection, | ||
| SIGNAL_R_CONTEXT_INITIAL_STATE, | ||
| SignalRActionsContext, | ||
| SignalRStateContext, | ||
| } from './contexts'; | ||
| import { signalRReducer } from './reducer'; | ||
| import { setConnectionAction } from './actions'; | ||
| import { useSheshaApplication } from '../sheshaApplication'; | ||
|
|
||
| const DEFAULT_RECONNECT_INTERVALS = [0, 2000, 5000, 10000]; | ||
|
|
||
| export interface ISignalRProvider { | ||
| hubUrl: string; | ||
| baseUrl?: string; | ||
| onConnected?: (connection: ISignalRConnection) => void; | ||
| onDisconnected?: () => void; | ||
| enableReconnect?: boolean; | ||
| reconnectIntervals?: number[]; // default: [0, 2000, 5000, 10000] | ||
| } | ||
|
|
||
| function SignalRProvider({ | ||
|
Check failure on line 26 in shesha-reactjs/src/providers/signalR/index.tsx
|
||
| children, | ||
| baseUrl, | ||
| hubUrl, | ||
| onConnected, | ||
| onDisconnected, | ||
| enableReconnect, | ||
| reconnectIntervals, | ||
| }: PropsWithChildren<ISignalRProvider>) { | ||
| const [state, dispatch] = useReducer(signalRReducer, { ...SIGNAL_R_CONTEXT_INITIAL_STATE }); | ||
| const { backendUrl } = useSheshaApplication(); | ||
|
|
||
| const setConnection = (connection?: ISignalRConnection) => { | ||
| dispatch(setConnectionAction(connection)); | ||
| }; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Keep the latest callbacks in refs so the SignalR event handlers always invoke the | ||
| // current callbacks without having to list them as effect deps (which would tear down | ||
| // and rebuild the connection whenever the parent passes new callback identities). | ||
| const onConnectedRef = useRef(onConnected); | ||
| const onDisconnectedRef = useRef(onDisconnected); | ||
|
|
||
| useEffect(() => { | ||
| onConnectedRef.current = onConnected; | ||
| onDisconnectedRef.current = onDisconnected; | ||
| }); | ||
|
|
||
| // Depend on the reconnect interval *values*, not the array's identity, so passing a new | ||
| // array literal with the same values doesn't needlessly recreate the connection. | ||
| const reconnectIntervalsKey = (reconnectIntervals ?? DEFAULT_RECONNECT_INTERVALS).join(','); | ||
|
|
||
| useEffect(() => { | ||
| // Guards against a start() that resolves after this effect has been cleaned up, | ||
| // which would otherwise push an already-stopped connection back into state. | ||
| let isActive = true; | ||
|
|
||
| let builder = new signalR.HubConnectionBuilder().withUrl(`${baseUrl ?? backendUrl}${hubUrl}`); | ||
|
|
||
| if (enableReconnect) { | ||
| builder = builder.withAutomaticReconnect(reconnectIntervals ?? DEFAULT_RECONNECT_INTERVALS); | ||
| } | ||
|
|
||
| const connection: ISignalRConnection = builder.build(); | ||
|
|
||
| if (enableReconnect) { | ||
| connection.onreconnecting((error) => { | ||
|
Check failure on line 71 in shesha-reactjs/src/providers/signalR/index.tsx
|
||
| console.warn('SignalR reconnecting...', error); | ||
| }); | ||
|
|
||
| connection.onreconnected(() => { | ||
|
Check failure on line 75 in shesha-reactjs/src/providers/signalR/index.tsx
|
||
| onConnectedRef.current?.(connection); | ||
| }); | ||
| } | ||
|
|
||
| connection.onclose((error) => { | ||
| console.error('SignalR connection closed', error); | ||
| onDisconnectedRef.current?.(); | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| connection | ||
| .start() | ||
| .then(() => { | ||
| // Only expose the connection once it has actually started successfully, | ||
| // and only if this effect instance is still active. | ||
| if (!isActive) return; | ||
| setConnection(connection); | ||
| onConnectedRef.current?.(connection); | ||
| }) | ||
| .catch((err) => console.error('SignalR start failed:', err)); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| return () => { | ||
| isActive = false; | ||
| // No need to call onDisconnected here — stop() triggers onclose, which already | ||
| // invokes onDisconnectedRef.current. If the connection never started, neither | ||
| // fires, mirroring the fact that onConnected was never called either. | ||
| connection | ||
| ?.stop() | ||
| ?.catch((err) => console.error('SignalRProvider connection error', err)); | ||
|
|
||
| setConnection(); | ||
| }; | ||
| }, [baseUrl, backendUrl, hubUrl, enableReconnect, reconnectIntervalsKey]); | ||
|
|
||
| /* NEW_ACTION_DECLARATION_GOES_HERE */ | ||
|
|
||
| return ( | ||
| <SignalRStateContext.Provider value={state}> | ||
| <SignalRActionsContext.Provider | ||
| value={{ | ||
| ...getFlagSetters(dispatch), | ||
| /* NEW_ACTION_GOES_HERE */ | ||
| }} | ||
| > | ||
| {children} | ||
| </SignalRActionsContext.Provider> | ||
| </SignalRStateContext.Provider> | ||
| ); | ||
| } | ||
|
|
||
| function useSignalRState(require: boolean) { | ||
| const context = useContext(SignalRStateContext); | ||
|
|
||
| if (context === undefined && require) { | ||
| throw new Error('useSignalRState must be used within a SignalRProvider'); | ||
| } | ||
|
|
||
| return context; | ||
| } | ||
|
|
||
| function useSignalRActions(require: boolean) { | ||
| const context = useContext(SignalRActionsContext); | ||
|
|
||
| if (context === undefined && require) { | ||
| throw new Error('useSignalRActions must be used within a SignalRProvider'); | ||
| } | ||
|
|
||
| return context; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| function useSignalR(require: boolean = true) { | ||
| const actionsContext = useSignalRActions(require); | ||
| const stateContext = useSignalRState(require); | ||
|
|
||
| // useContext() returns initial state when provider is missing | ||
| // initial context state is useless especially when require == true | ||
| // so we must return value only when both context are available | ||
| return actionsContext !== undefined && stateContext !== undefined | ||
| ? { ...actionsContext, ...stateContext } | ||
| : undefined; | ||
| } | ||
|
|
||
| export default SignalRProvider; | ||
|
|
||
| export { SignalRProvider, useSignalR, useSignalRActions, useSignalRState }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.