Skip to content

Commit

Permalink
feat: createLocalStorage, createSessionStorage 유틸 함수 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
YuHyun-P committed Feb 3, 2024
1 parent 14c8602 commit 05b4bab
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions packages/frontend/src/utils/webStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
export function createLocalStorage<Value>(key: string, defaultValue: Value) {
return createStorage({ type: "localStorage", key, defaultValue });
}

export function createSessionStorage<Value>(key: string, defaultValue: Value) {
return createStorage<Value>({ type: "sessionStorage", key, defaultValue });
}

type CreateStorageOptions<Value> = {
type: "localStorage" | "sessionStorage";
key: string;
defaultValue: Value;
};

function createStorage<Value>({
type,
key,
defaultValue,
}: CreateStorageOptions<Value>) {
const getItem = (): Value => {
const value = window?.[type].getItem(key);

if (value === null) return defaultValue;

try {
const parsedValue = JSON.parse(value);
return parsedValue as Value;
} catch (error) {
return defaultValue;
}
};

const setItem = (value: Value) =>
window?.[type].setItem(key, JSON.stringify(value));

const removeItem = () => window?.[type].removeItem(key);

return {
getItem,
setItem,
removeItem,
};
}

0 comments on commit 05b4bab

Please sign in to comment.