From f1a37e06bc177a547960741b5658efd743f03da4 Mon Sep 17 00:00:00 2001 From: soham <68921363+sohzm@users.noreply.github.com> Date: Tue, 27 Feb 2024 03:21:27 +0530 Subject: [PATCH] Fix multiple timer issue in CopyButton by using useRef (#26285) * Fix multiple timer issue in CopyButton by using useRef This commit resolves a bug where rapidly clicking the Copy button in the CopyButton component would initiate multiple overlapping timers, leading to unpredictable copy state toggling. By utilizing useRef, we now ensure a single timer instance is managed and cleared appropriately, stabilizing the copy functionality. * Remove null assignment to timerRef.current before setting new timeout --------- Co-authored-by: Mattermost Build --- webapp/channels/src/components/copy_button.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/webapp/channels/src/components/copy_button.tsx b/webapp/channels/src/components/copy_button.tsx index 1f9bf5881a..ed47078b9b 100644 --- a/webapp/channels/src/components/copy_button.tsx +++ b/webapp/channels/src/components/copy_button.tsx @@ -2,7 +2,7 @@ // See LICENSE.txt for license information. import classNames from 'classnames'; -import React, {useState} from 'react'; +import React, {useRef, useState} from 'react'; import {Tooltip} from 'react-bootstrap'; import {FormattedMessage} from 'react-intl'; @@ -22,12 +22,17 @@ type Props = { const CopyButton: React.FC = (props: Props) => { const [isCopied, setIsCopied] = useState(false); + const timerRef = useRef(null); const copyText = (e: React.MouseEvent): void => { e.preventDefault(); setIsCopied(true); - setTimeout(() => { + if (timerRef.current) { + clearTimeout(timerRef.current); + } + + timerRef.current = setTimeout(() => { setIsCopied(false); }, 2000);