Skip to content

Commit 678adf6

Browse files
memoize TokenSource.custom
1 parent b7d411b commit 678adf6

File tree

1 file changed

+33
-29
lines changed

1 file changed

+33
-29
lines changed

hooks/useRoom.ts

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -36,36 +36,40 @@ export function useRoom(appConfig: AppConfig) {
3636
};
3737
}, [room]);
3838

39-
const startSession = useCallback(() => {
40-
setIsSessionActive(true);
39+
const tokenSource = useMemo(
40+
() =>
41+
TokenSource.custom(async () => {
42+
const url = new URL(
43+
process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT ?? '/api/connection-details',
44+
window.location.origin
45+
);
4146

42-
const tokenSource = TokenSource.custom(async () => {
43-
const url = new URL(
44-
process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT ?? '/api/connection-details',
45-
window.location.origin
46-
);
47+
try {
48+
const res = await fetch(url.toString(), {
49+
method: 'POST',
50+
headers: {
51+
'Content-Type': 'application/json',
52+
'X-Sandbox-Id': appConfig.sandboxId ?? '',
53+
},
54+
body: JSON.stringify({
55+
room_config: appConfig.agentName
56+
? {
57+
agents: [{ agent_name: appConfig.agentName }],
58+
}
59+
: undefined,
60+
}),
61+
});
62+
return await res.json();
63+
} catch (error) {
64+
console.error('Error fetching connection details:', error);
65+
throw new Error('Error fetching connection details!');
66+
}
67+
}),
68+
[appConfig]
69+
);
4770

48-
try {
49-
const res = await fetch(url.toString(), {
50-
method: 'POST',
51-
headers: {
52-
'Content-Type': 'application/json',
53-
'X-Sandbox-Id': appConfig.sandboxId ?? '',
54-
},
55-
body: JSON.stringify({
56-
room_config: appConfig.agentName
57-
? {
58-
agents: [{ agent_name: appConfig.agentName }],
59-
}
60-
: undefined,
61-
}),
62-
});
63-
return await res.json();
64-
} catch (error) {
65-
console.error('Error fetching connection details:', error);
66-
throw new Error('Error fetching connection details!');
67-
}
68-
});
71+
const startSession = useCallback(() => {
72+
setIsSessionActive(true);
6973

7074
if (room.state === 'disconnected') {
7175
const { isPreConnectBufferEnabled } = appConfig;
@@ -94,7 +98,7 @@ export function useRoom(appConfig: AppConfig) {
9498
});
9599
});
96100
}
97-
}, [room, appConfig]);
101+
}, [room, appConfig, tokenSource]);
98102

99103
const endSession = useCallback(() => {
100104
setIsSessionActive(false);

0 commit comments

Comments
 (0)