Skip to content

Commit

Permalink
fix: doble execution of onPause on useStopwatch #33
Browse files Browse the repository at this point in the history
  • Loading branch information
dlcastillop committed Apr 6, 2024
1 parent 9352f16 commit 7998458
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/helpers/useInternalStopwatch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { addLeadingZero, parseTime } from "../helpers";
import { InternalCounter, StopwatchOptions } from "../interfaces";

Expand All @@ -16,6 +16,7 @@ export const useInternalStopwatch = (
const [paused, setPaused] = useState(startPaused ?? false);
const divider = separator ?? ":";
const [isOver, setIsOver] = useState(false);
const wasPausedRef = useRef(startPaused ?? false);

useEffect(() => {
if (paused) {
Expand Down Expand Up @@ -69,6 +70,13 @@ export const useInternalStopwatch = (
isOver && onFinish && onFinish();
}, [isOver]);

useEffect(() => {
if (!wasPausedRef.current && paused) {
onPause && onPause();
}
wasPausedRef.current = paused;
}, [paused, onPause]);

return {
current: {
withLeadingZero: `${addLeadingZero(time.days)}${divider}${addLeadingZero(
Expand Down Expand Up @@ -98,7 +106,6 @@ export const useInternalStopwatch = (
: 0,
pause: () => {
setPaused(true);
onPause && onPause();
},
play: () => setPaused(false),
reset: () => {
Expand Down

0 comments on commit 7998458

Please sign in to comment.