apollo-feature-requests
apollo-feature-requests copied to clipboard
[react] Allow reconnect after error using the useSubscription hook
If the useSubscription hook returns an error, then the subscription is lost with no way of reconnecting.
Currently we're using using the client directly and using a hacky solution to create a new subscription after a timeout when it disconnects:
export function useReconnectingSubscription() {
// retry switch is used to trigger rerenders when the subscription errors
const [retrySwitch, setRetrySwitch] = useState(true);
const [data, setData] = useState();
const client = useApolloClient();
useEffect(() => {
const observer = client.subscribe({ query });
const subscription = observer.subscribe(
({ data }) => {
setData(data ? data.notifications : undefined);
},
(error) => {
if (error && subscription.closed) {
noticeError(error);
setTimeout(() => {
// retry subscription connection after 10s
setRetrySwitch(!retrySwitch);
}, 10000);
}
},
);
return () => subscription.unsubscribe();
}, [retrySwitch]);
return data;
}
Suggestion
The useSubscription hook could return a reconnect function in a similar fashion to the refetch option on useQuery. Calling this could either update the existing observer, or create a new one.