How to remove event listener when a prop is false

138 Views Asked by At

When I lock the statement, the timer starts after 5s of mouse inactivity. But when the statement is unlock, I don't want that timer to keep running. However, in debug when the prop isLocked is false it enters in the else, but event doesn't seem to be removed, because it starts after 5s of mouse inactivity. I'm using react-timer-hook.

Do you have any suggestions? Here is my code

function LockSection(props: ILockSection, expiryTimestamp: any, autoStart: boolean) {

    autoStart = false;
    expiryTimestamp = new Date();
    expiryTimestamp.setSeconds(expiryTimestamp.getSeconds() + 75);

    const {
        seconds,
        minutes,
        start,
        restart,
    } = useTimer({ expiryTimestamp, onExpire: props.setLockedFunction, autoStart });

    const resetStartTimer = () => {
        const time = new Date();
        time.setSeconds(time.getSeconds() + 75);
        clearTimeout(0);
        restart(time, false);
        setTimeout(start, 5000);
    };

    useEffect(() => {
        if (props.isLocked) {
            window.addEventListener('mousemove', resetStartTimer);
        } else {
            window.removeEventListener('mousemove', resetStartTimer);
        }

        return () => {
            window.removeEventListener('mousemove', resetStartTimer);
        };

    }, [props.isLocked]);

    function lockStart() {
        props.setLockedFunction();
        
    }

    function unlockStop() {
        props.setLockedFunction();
        const time = new Date();
        time.setSeconds(time.getSeconds() + 75);
        restart(time, false);
    }

    return (
        <div className="lock-section">
           
            {!props.isLocked && props.userCanLock && <Button variant="info" onClick={lockStart}>Edit Statement</Button>}

            {props.isLocked && props.userCanLock && <div className="locked-by-user">
                <Button className="button-unlock" variant="info" onClick={unlockStop}>Unlock Statement</Button>
                <div className="form-control lockTimer">Timer&nbsp;{minutes < 10 && <span>0</span>}<span> {minutes}</span>: {seconds < 10 && <span>0</span>}<span>{seconds}</span></div> </div>}
            
            <TimerPopup triggerPopUp={minutes < 1} modalHeader={"Edit session is timing out"}
                modalBody={"Your changes will be lost."} />

            {!props.userCanLock && <div className="form-control locked">Statement already locked by {props.lockedByUser}</div>}
        </div>

    );
}

Thanks

0

There are 0 best solutions below