Skip to content

Commit 0e14acc

Browse files
committed
fix: guard against fetching appsettings many times (#3095)
1 parent 83d594f commit 0e14acc

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

package/src/components/Chat/hooks/useAppSettings.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from 'react';
1+
import { useEffect, useRef, useState } from 'react';
22

33
import type { AppSettingsAPIResponse, StreamChat } from 'stream-chat';
44

@@ -15,9 +15,18 @@ export const useAppSettings = <
1515
initialisedDatabase: boolean,
1616
): AppSettingsAPIResponse | null => {
1717
const [appSettings, setAppSettings] = useState<AppSettingsAPIResponse | null>(null);
18+
const appSettingsPromise = useRef<Promise<AppSettingsAPIResponse | null>>(null);
19+
const fetchedAppSettings = useRef(false);
1820
const isMounted = useIsMountedRef();
1921

2022
useEffect(() => {
23+
const fetchAppSettings = () => {
24+
if (appSettingsPromise.current) {
25+
return appSettingsPromise.current;
26+
}
27+
appSettingsPromise.current = client.getAppSettings();
28+
return appSettingsPromise.current;
29+
};
2130
/**
2231
* Fetches app settings from the backend when offline support is disabled.
2332
*/
@@ -27,9 +36,10 @@ export const useAppSettings = <
2736
}
2837

2938
try {
30-
const appSettings = await client.getAppSettings();
39+
const appSettings = await fetchAppSettings();
3140
if (isMounted.current) {
3241
setAppSettings(appSettings);
42+
fetchedAppSettings.current = true;
3343
}
3444
} catch (error: unknown) {
3545
if (error instanceof Error) {
@@ -59,9 +69,10 @@ export const useAppSettings = <
5969
}
6070

6171
try {
62-
const appSettings = await client.getAppSettings();
63-
if (isMounted.current) {
72+
const appSettings = await fetchAppSettings();
73+
if (isMounted.current && appSettings) {
6474
setAppSettings(appSettings);
75+
fetchedAppSettings.current = true;
6576
await dbApi.upsertAppSettings({
6677
appSettings,
6778
currentUserId: client.userID as string,
@@ -75,6 +86,10 @@ export const useAppSettings = <
7586
};
7687

7788
async function enforeAppSettings() {
89+
if (fetchedAppSettings.current) {
90+
return;
91+
}
92+
7893
if (enableOfflineSupport) {
7994
await enforceAppSettingsWithOfflineSupport();
8095
} else {

0 commit comments

Comments
 (0)