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 <build@mattermost.com>
This commit is contained in:
soham 2024-02-27 03:21:27 +05:30 committed by GitHub
parent d788ece25d
commit f1a37e06bc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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: Props) => {
const [isCopied, setIsCopied] = useState(false);
const timerRef = useRef<NodeJS.Timeout | null>(null);
const copyText = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>): void => {
e.preventDefault();
setIsCopied(true);
setTimeout(() => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
setIsCopied(false);
}, 2000);