Skip to content

fix: using ref to solve closure problems #497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/cookies/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ const useCookieListener = (
options: ICookieOptions = defaultOptions
) => {
const { timeout, immediately } = options;
const isWatchAll = !watchFields.length;
const timerRef = useRef<number>();
const currentCookiesRef = useRef<string>(document.cookie);
const isWatchAll = !watchFields.length;
const handlerRef = useRef<CompareCookieHandler>();
handlerRef.current = handler;

useEffect(() => {
timerRef.current = window.setInterval(() => {
Expand All @@ -54,15 +56,15 @@ const useCookieListener = (
changedFields.push({ key, value: newValue });
}
}
changedFields.length && handler({ changedFields, prevCookies, nextCookies });
changedFields.length && handlerRef.current?.({ changedFields, prevCookies, nextCookies });
};

const compareValue = () => {
const prevCookies = currentCookiesRef.current;
const nextCookies = document.cookie;
if (prevCookies !== nextCookies) {
isWatchAll
? handler({ prevCookies, nextCookies })
? handlerRef.current?.({ prevCookies, nextCookies })
: handleFieldsChange(prevCookies, nextCookies);
currentCookiesRef.current = nextCookies;
}
Expand Down
Loading