From c0874bd6328c88ecf8dab13c8142d24973af49ca Mon Sep 17 00:00:00 2001 From: Daniel Castillo Date: Sat, 6 Apr 2024 07:40:23 -0400 Subject: [PATCH] fix: doble execution of onPause on useCountDown and useCountUp #33 --- src/App.tsx | 4 ++-- src/helpers/useCounter.ts | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 7840899..78bb958 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,8 +1,8 @@ -import { useStopwatch } from "./hooks"; +import { useCountDown } from "./hooks"; const App = () => { const { current, isPaused, isOver, pause, play, reset, togglePause } = - useStopwatch(); + useCountDown(1, 10); return (
diff --git a/src/helpers/useCounter.ts b/src/helpers/useCounter.ts index b6247b2..21dac2a 100644 --- a/src/helpers/useCounter.ts +++ b/src/helpers/useCounter.ts @@ -1,4 +1,4 @@ -import { useState, useEffect } from "react"; +import { useState, useEffect, useRef } from "react"; import { BaseCounter, BaseCounterOptions } from "../interfaces"; import { addLeadingZero } from "."; @@ -16,6 +16,7 @@ export const useCounter = ( const [count, setCount] = useState(isCountingUp ? min : max); const [paused, setPaused] = useState(startPaused ?? false); const [isOver, setIsOver] = useState(false); + const wasPausedRef = useRef(startPaused ?? false); useEffect(() => { if (paused) { @@ -42,8 +43,11 @@ export const useCounter = ( }, [isOver]); useEffect(() => { - paused && onPause && onPause(); - }, [paused]); + if (!wasPausedRef.current && paused) { + onPause && onPause(); + } + wasPausedRef.current = paused; + }, [paused, onPause]); return { current: {