Skip to content

Commit 8e63653

Browse files
fix(useCooldownTimer): derive cooldown from last message (#1879)
1 parent 836df66 commit 8e63653

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

src/components/MessageInput/hooks/useCooldownTimer.tsx

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

33
import { useChatContext } from '../../../context/ChatContext';
44
import { useChannelStateContext } from '../../../context/ChannelStateContext';
@@ -17,30 +17,36 @@ export const useCooldownTimer = <
1717
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
1818
>(): CooldownTimerState => {
1919
const { latestMessageDatesByChannels } = useChatContext<StreamChatGenerics>('useCooldownTimer');
20-
const { channel } = useChannelStateContext<StreamChatGenerics>('useCooldownTimer');
20+
const { channel, messages = [] } = useChannelStateContext<StreamChatGenerics>('useCooldownTimer');
21+
const { client } = useChatContext<StreamChatGenerics>('useCooldownTimer');
22+
const [cooldownRemaining, setCooldownRemaining] = useState<number>();
2123

2224
const { cooldown: cooldownInterval, own_capabilities } = (channel.data ||
2325
{}) as ChannelResponse<StreamChatGenerics>;
2426

25-
const [cooldownRemaining, setCooldownRemaining] = useState<number>();
26-
2727
const skipCooldown = !own_capabilities?.includes('slow-mode');
2828

29+
const ownLatestMessageDate = useMemo(
30+
() =>
31+
latestMessageDatesByChannels[channel.cid] ??
32+
[...messages]
33+
.sort((a, b) => (b.created_at as Date)?.getTime() - (a.created_at as Date)?.getTime())
34+
.find((v) => v.user?.id === client.user?.id)?.created_at,
35+
[messages, client.user?.id, latestMessageDatesByChannels, channel.cid],
36+
) as Date;
37+
2938
useEffect(() => {
30-
const latestMessageDate = latestMessageDatesByChannels[channel.cid];
31-
if (!cooldownInterval || !latestMessageDate) {
32-
return;
33-
}
39+
if (skipCooldown || !cooldownInterval || !ownLatestMessageDate) return;
40+
3441
const remainingCooldown = Math.round(
35-
cooldownInterval - (new Date().getTime() - latestMessageDate.getTime()) / 1000,
42+
cooldownInterval - (new Date().getTime() - ownLatestMessageDate.getTime()) / 1000,
3643
);
37-
if (remainingCooldown > 0 && !skipCooldown) {
38-
setCooldownRemaining(remainingCooldown);
39-
}
40-
}, [channel.id, cooldownInterval, latestMessageDatesByChannels[channel.cid]]);
44+
45+
if (remainingCooldown > 0) setCooldownRemaining(remainingCooldown);
46+
}, [cooldownInterval, ownLatestMessageDate, skipCooldown]);
4147

4248
return {
43-
cooldownInterval: cooldownInterval || 0,
49+
cooldownInterval: cooldownInterval ?? 0,
4450
cooldownRemaining,
4551
setCooldownRemaining,
4652
};

0 commit comments

Comments
 (0)