Skip to content

Commit 50dce01

Browse files
authored
Merge pull request #10474 from daily-co/pre-1151
PRE-1151 Correctly handle unmounted and remounted useCallInstance
2 parents 23e9262 + 5536c20 commit 50dce01

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/hooks/useCallInstance.ts

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,30 @@ export const useCallInstance = (
5151
await co.destroy();
5252
}
5353

54+
/**
55+
* Once instance is destroyed, nullify callInstance, so a new one can be created.
56+
*/
57+
const handleDestroyedInstance = () => {
58+
/**
59+
* Setting a timeout makes sure the destruction and creation
60+
* of call instances happen in separate call stacks.
61+
* Otherwise there's a risk for duplicate call instances.
62+
*/
63+
setTimeout(() => setCallInstance(null), 0);
64+
};
65+
66+
let co = Daily.getCallInstance();
67+
68+
/**
69+
* In case a call instance exists outside of this hook instance's knowledge,
70+
* store it in state.
71+
*/
72+
if (!callInstance && co && !co.isDestroyed()) {
73+
co.once('call-instance-destroyed', handleDestroyedInstance);
74+
setCallInstance(co);
75+
return;
76+
}
77+
5478
/**
5579
* callInstance exists.
5680
*/
@@ -67,7 +91,6 @@ export const useCallInstance = (
6791
return;
6892
}
6993

70-
let co = Daily.getCallInstance();
7194
if (!co || co.isDestroyed()) {
7295
/**
7396
* callInstance doesn't exist or is destroyed (TODO: Check why getCallInstance() can return a destroyed instance),
@@ -89,12 +112,7 @@ export const useCallInstance = (
89112

90113
setCallInstance(co);
91114

92-
/**
93-
* Once instance is destroyed, nullify callInstance, so a new one is created.
94-
*/
95-
co.once('call-instance-destroyed', () => {
96-
setCallInstance(null);
97-
});
115+
co.once('call-instance-destroyed', handleDestroyedInstance);
98116

99117
/**
100118
* No cleanup phase here, because callObject.destroy() returns a Promise.

0 commit comments

Comments
 (0)