Skip to content

Commit a15db42

Browse files
committed
refactor: add callback to avoid complexity
1 parent 51dccba commit a15db42

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

src/WorkflowManager.tsx

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -37,24 +37,6 @@ export const WorkflowManager: FC<WorkflowManagerProps> = ({
3737
if (status !== 'connected') setStatus('connected');
3838
});
3939

40-
mqttInstance.on('end', () => {
41-
if (status !== 'offline') setStatus('offline');
42-
});
43-
44-
mqttInstance.on('offline', () => {
45-
if (status !== 'offline') setStatus('offline');
46-
});
47-
48-
mqttInstance.on('error', () => {
49-
if (status !== 'error') setStatus('error');
50-
setError(new Error(ERROR_MESSAGES.ERROR_OCURRED));
51-
invariant(false, ERROR_MESSAGES.ERROR_OCURRED);
52-
});
53-
54-
mqttInstance.on('reconnect', () => {
55-
if (status !== 'reconnecting') setStatus('reconnecting');
56-
});
57-
5840
setClient(mqttInstance);
5941
WorkflowManagerConfig.setMqttClient(mqttInstance);
6042
} catch (error) {
@@ -65,10 +47,36 @@ export const WorkflowManager: FC<WorkflowManagerProps> = ({
6547
}
6648
}, [brokerUrl, options, client, status]);
6749

50+
const onConnected = useCallback(() => {
51+
if (client && status !== 'connected' && !connectionOpen.current) {
52+
client.on('end', () => {
53+
if (status !== 'offline') setStatus('offline');
54+
});
55+
56+
client.on('offline', () => {
57+
if (status !== 'offline') setStatus('offline');
58+
});
59+
60+
client.on('error', () => {
61+
if (status !== 'error') setStatus('error');
62+
setError(new Error(ERROR_MESSAGES.ERROR_OCURRED));
63+
invariant(false, ERROR_MESSAGES.ERROR_OCURRED);
64+
});
65+
66+
client.on('reconnect', () => {
67+
if (status !== 'reconnecting') setStatus('reconnecting');
68+
});
69+
}
70+
}, [client, status]);
71+
6872
useEffect(() => {
6973
init();
7074
}, [init]);
7175

76+
useEffect(() => {
77+
onConnected();
78+
}, [onConnected]);
79+
7280
useEffect(() => {
7381
return () => {
7482
if (client) {

0 commit comments

Comments
 (0)