Skip to content
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

Feat/use cookie #578

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
22 changes: 22 additions & 0 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^14.3.1",
"@testing-library/user-event": "^14.5.1",
"@types/js-cookie": "^3",
"@types/lodash-es": "^4",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@types/ua-parser-js": "^0.7.39",
"@vitest/coverage-istanbul": "^2.1.3",
"classnames": "^2.5.1",
"esbuild": "^0.24.0",
"js-cookie": "^3.0.5",
"jsdom": "^25.0.0",
"lodash-es": "^4.17.21",
"postcss": "^8.4.41",
Expand Down
13 changes: 13 additions & 0 deletions packages/react/src/_internal/storage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const CUSTOM_EVENT_KEYS = {
localStorage: 'modern-kit-local-storage',
sessionStorage: 'modern-kit-session-storage',
cookie: 'modern-kit-cookie',
} as const;

const customEventHandler = {
Expand Down Expand Up @@ -30,6 +31,18 @@ const customEventHandler = {
);
},
},
cookie: {
key: CUSTOM_EVENT_KEYS['cookie'],
subscribe: (callback: () => void) => {
window.addEventListener(CUSTOM_EVENT_KEYS['cookie'], callback);
},
unsubscribe: (callback: () => void) => {
window.removeEventListener(CUSTOM_EVENT_KEYS['cookie'], callback);
},
dispatchEvent: () => {
window.dispatchEvent(new StorageEvent(CUSTOM_EVENT_KEYS['cookie']));
},
},
};

export const getCustomEventHandler = (key: keyof typeof CUSTOM_EVENT_KEYS) => {
Expand Down
101 changes: 101 additions & 0 deletions packages/react/src/hooks/useCookie/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { isFunction } from '@modern-kit/utils';
import { usePreservedState } from '../../hooks/usePreservedState';
import {
Dispatch,
SetStateAction,
useCallback,
useSyncExternalStore,
} from 'react';
import {
cookieEventHandler,
subscribe,
getSnapshot,
getServerSnapshot,
} from './useCookie.utils';
import Cookies, { CookieAttributes } from 'js-cookie';

interface UseCookieWithoutInitialValueProps {
key: string;
}

interface UseCookieWithInitialValueProps {
key: string;
initialValue: string | (() => string);
}

type UseCookieProps =
| UseCookieWithoutInitialValueProps
| UseCookieWithInitialValueProps;

// 함수 오버로딩
export function useCookie({
key,
initialValue,
}: UseCookieWithInitialValueProps): {
state: string;
setState: Dispatch<SetStateAction<string>>;
removeState: () => void;
getAllCookies: () => Record<string, string>;
};

export function useCookie({ key }: UseCookieWithoutInitialValueProps): {
state: string | null;
setState: Dispatch<SetStateAction<string>>;
removeState: () => void;
getAllCookies: () => Record<string, string>;
};

export function useCookie(props: UseCookieProps) {
const { key } = props;

const initialValue = 'initialValue' in props ? props.initialValue : null;

const initialValueToUse = usePreservedState(
isFunction(initialValue) ? initialValue() : initialValue
);

const externalStoreState = useSyncExternalStore(
subscribe,
() => getSnapshot(key),
() => getServerSnapshot(initialValueToUse)
);

const setState = useCallback(
(value: SetStateAction<string>, options?: CookieAttributes) => {
try {
const prevStateString = getSnapshot(key);
const valueToUse = isFunction(value)
? value(prevStateString ?? initialValueToUse ?? '')
: value;

Cookies.set(key, valueToUse, options);
cookieEventHandler.dispatchEvent();
} catch (err) {
throw new Error(
`Failed to store data for key "${key}" in cookie: ${err}`
);
}
},
[key]

Check warning on line 79 in packages/react/src/hooks/useCookie/index.ts

View workflow job for this annotation

GitHub Actions / Build-Test

React Hook useCallback has a missing dependency: 'initialValueToUse'. Either include it or remove the dependency array
);

const removeState = useCallback(() => {
try {
cookieEventHandler.dispatchEvent();
Cookies.remove(key);
} catch (err) {
throw new Error(`Failed to remove key "${key}" from cookie: ${err}`);
}
}, [key]);

const getAllCookies = useCallback(() => {
return Cookies.get();
}, []);

return {
state: externalStoreState ?? initialValueToUse,
setState,
removeState,
getAllCookies,
};
}
20 changes: 20 additions & 0 deletions packages/react/src/hooks/useCookie/useCookie.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Cookies from 'js-cookie';
import { getCustomEventHandler } from '../../_internal/storage';

export const cookieEventHandler = getCustomEventHandler('cookie');

export const getSnapshot = (key: string) => {
return Cookies.get(key);
};

// SSR 환경에서 initialValue를 반환
export const getServerSnapshot = (initialValue: string | null) => {
return initialValue;
};

export const subscribe = (callback: () => void) => {
cookieEventHandler.subscribe(callback);
return () => {
cookieEventHandler.unsubscribe(callback);
};
};
2 changes: 1 addition & 1 deletion packages/react/src/hooks/useLocalStorage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function useLocalStorage<T>(props: UseLocalStorageProps<T>) {
}, [externalStoreState, initialValueToUse]);

const setState = useCallback(
(value: Dispatch<SetStateAction<T | null>>) => {
(value: SetStateAction<T | null>) => {
try {
const prevStateString = getSnapshot(key);
const prevState = prevStateString
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/hooks/useSessionStorage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function useSessionStorage<T>(props: UseSessionStorageProps<T>) {
}, [externalStoreState, initialValueToUse]);

const setState = useCallback(
(value: Dispatch<SetStateAction<T | null>>) => {
(value: SetStateAction<T | null>) => {
try {
const prevStateString = getSnapshot(key);
const prevState = prevStateString
Expand Down
16 changes: 16 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4972,13 +4972,15 @@ __metadata:
"@testing-library/jest-dom": "npm:^6.5.0"
"@testing-library/react": "npm:^14.3.1"
"@testing-library/user-event": "npm:^14.5.1"
"@types/js-cookie": "npm:^3"
"@types/lodash-es": "npm:^4"
"@types/react": "npm:^18.2.20"
"@types/react-dom": "npm:^18.2.7"
"@types/ua-parser-js": "npm:^0.7.39"
"@vitest/coverage-istanbul": "npm:^2.1.3"
classnames: "npm:^2.5.1"
esbuild: "npm:^0.24.0"
js-cookie: "npm:^3.0.5"
jsdom: "npm:^25.0.0"
lodash-es: "npm:^4.17.21"
postcss: "npm:^8.4.41"
Expand Down Expand Up @@ -6446,6 +6448,13 @@ __metadata:
languageName: node
linkType: hard

"@types/js-cookie@npm:^3":
version: 3.0.6
resolution: "@types/js-cookie@npm:3.0.6"
checksum: 173afaf5ea9d86c22395b9d2a00b6adb0006dcfef165d6dcb0395cdc32f5a5dcf9c3c60f97194119963a15849b8f85121e1ae730b03e40bc0c29b84396ba22f9
languageName: node
linkType: hard

"@types/json-schema@npm:*, @types/json-schema@npm:^7.0.15, @types/json-schema@npm:^7.0.4, @types/json-schema@npm:^7.0.5, @types/json-schema@npm:^7.0.8":
version: 7.0.15
resolution: "@types/json-schema@npm:7.0.15"
Expand Down Expand Up @@ -14292,6 +14301,13 @@ __metadata:
languageName: node
linkType: hard

"js-cookie@npm:^3.0.5":
version: 3.0.5
resolution: "js-cookie@npm:3.0.5"
checksum: 04a0e560407b4489daac3a63e231d35f4e86f78bff9d792011391b49c59f721b513411cd75714c418049c8dc9750b20fcddad1ca5a2ca616c3aca4874cce5b3a
languageName: node
linkType: hard

"js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0":
version: 4.0.0
resolution: "js-tokens@npm:4.0.0"
Expand Down