Skip to content

Commit 33411b8

Browse files
authored
fix: prevent duplicate simultaneous query channel quests (#2004)
1 parent 3796393 commit 33411b8

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/components/ChannelList/utils.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,23 @@
1-
import type { Channel, StreamChat } from 'stream-chat';
1+
import type { Channel, QueryChannelAPIResponse, StreamChat } from 'stream-chat';
22
import uniqBy from 'lodash.uniqby';
33

44
import type { DefaultStreamChatGenerics } from '../../types/types';
55

6+
/**
7+
* prevent from duplicate invocation of channel.watch()
8+
* when events 'notification.message_new' and 'notification.added_to_channel' arrive at the same time
9+
*/
10+
const WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL: Record<
11+
string,
12+
Promise<QueryChannelAPIResponse> | undefined
13+
> = {};
14+
15+
/**
16+
* Calls channel.watch() if it was not already recently called. Waits for watch promise to resolve even if it was invoked previously.
17+
* @param client
18+
* @param type
19+
* @param id
20+
*/
621
export const getChannel = async <
722
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
823
>(
@@ -11,7 +26,15 @@ export const getChannel = async <
1126
id: string,
1227
) => {
1328
const channel = client.channel(type, id);
14-
await channel.watch();
29+
const queryPromise = WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL[channel.cid];
30+
if (queryPromise) {
31+
await queryPromise;
32+
} else {
33+
WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL[channel.cid] = channel.watch();
34+
await WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL[channel.cid];
35+
WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL[channel.cid] = undefined;
36+
}
37+
1538
return channel;
1639
};
1740

0 commit comments

Comments
 (0)