fix error
This commit is contained in:
parent
9d682a8499
commit
0700e77a02
@ -15,21 +15,28 @@ export function useTimer({
|
|||||||
persist = false,
|
persist = false,
|
||||||
storageKey,
|
storageKey,
|
||||||
}: UseTimerOptions) {
|
}: UseTimerOptions) {
|
||||||
const [seconds, setSeconds] = useState<number>(() => {
|
// Always initialize with initialSeconds to match SSR
|
||||||
if (persist && storageKey) {
|
const [seconds, setSeconds] = useState<number>(initialSeconds);
|
||||||
const saved = localStorage.getItem(storageKey);
|
|
||||||
if (saved !== null) {
|
|
||||||
const parsed = parseInt(saved, 10);
|
|
||||||
if (!isNaN(parsed)) return parsed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return initialSeconds;
|
|
||||||
});
|
|
||||||
|
|
||||||
const intervalRef = useRef<NodeJS.Timeout | null>(null);
|
const intervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
|
// Load from localStorage after mount (client-only)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (persist && storageKey) {
|
if (persist && storageKey && typeof window !== 'undefined') {
|
||||||
|
const saved = localStorage.getItem(storageKey);
|
||||||
|
if (saved !== null) {
|
||||||
|
const parsed = parseInt(saved, 10);
|
||||||
|
if (!isNaN(parsed)) {
|
||||||
|
setSeconds(parsed);
|
||||||
|
return; // Don't save again if we just loaded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [persist, storageKey]); // Run once on mount
|
||||||
|
|
||||||
|
// Save to localStorage when seconds change
|
||||||
|
useEffect(() => {
|
||||||
|
if (persist && storageKey && typeof window !== 'undefined') {
|
||||||
localStorage.setItem(storageKey, seconds.toString());
|
localStorage.setItem(storageKey, seconds.toString());
|
||||||
}
|
}
|
||||||
}, [seconds, persist, storageKey]);
|
}, [seconds, persist, storageKey]);
|
||||||
@ -54,7 +61,7 @@ export function useTimer({
|
|||||||
|
|
||||||
const reset = useCallback(() => {
|
const reset = useCallback(() => {
|
||||||
setSeconds(initialSeconds);
|
setSeconds(initialSeconds);
|
||||||
if (persist && storageKey) {
|
if (persist && storageKey && typeof window !== 'undefined') {
|
||||||
localStorage.setItem(storageKey, initialSeconds.toString());
|
localStorage.setItem(storageKey, initialSeconds.toString());
|
||||||
}
|
}
|
||||||
}, [initialSeconds, persist, storageKey]);
|
}, [initialSeconds, persist, storageKey]);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user