Skip to content

Commit

Permalink
refactor: update setCookie function to accept minutes instead of hour…
Browse files Browse the repository at this point in the history
…s and adjust cookie persistence duration
  • Loading branch information
ericHgorski committed Nov 20, 2024
1 parent eee288c commit 8b45cfe
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
8 changes: 5 additions & 3 deletions src/hooks/useFeatureEnabled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,23 @@ import { getCookie, setCookie } from "@/utils/cookies";

export function useFeatureEnabled(featureName: string): boolean {
const [isFeatureEnabled, setIsFeatureEnabled] = useState(false);
const rolloutPercentage = parseInt(process.env.NEXT_PUBLIC_FEATURE_ROLLOUT_PERCENTAGE || "0", 10);

useEffect(() => {
if (typeof window !== "undefined") {
let featureEnabled = getCookie(featureName);
const rolloutPercentage = parseInt(process.env.NEXT_PUBLIC_FEATURE_ROLLOUT_PERCENTAGE || "0", 10);

if (featureEnabled === undefined) {
const randomNumber = Math.random() * 100;
featureEnabled = randomNumber < rolloutPercentage ? "true" : "false";
setCookie(featureName, featureEnabled);

// persist cookie for 5 minutes
setCookie(featureName, featureEnabled, 5);
}

setIsFeatureEnabled(featureEnabled === "true");
}
}, [featureName, rolloutPercentage]);
}, [featureName]);

return isFeatureEnabled;
}
6 changes: 3 additions & 3 deletions src/utils/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export const getCookie = (name: string): string | undefined => {
return undefined;
};

export const setCookie = (name: string, value: string, hours?: number): void => {
export const setCookie = (name: string, value: string, minutes?: number): void => {
let expires = "";
if (hours) {
if (minutes) {
const date = new Date();
date.setTime(date.getTime() + hours * 60 * 60 * 1000);
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = `; expires=${date.toUTCString()}`;
}
document.cookie = `${name}=${encodeURIComponent(value || "")}${expires}; path=/`;
Expand Down

0 comments on commit 8b45cfe

Please sign in to comment.