Skip to content

Commit

Permalink
SKRF-146 local storage 기능 추가 (#21)
Browse files Browse the repository at this point in the history
* feat : 스토리지 키 상수 저장

* feat : 로컬스토리지 관련 함수 추가

* fix : localStorage 에러 상황 변경
  • Loading branch information
hyesung99 authored Oct 25, 2023
1 parent 94f78c6 commit 0edaa9c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/constants/storageKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const STORAGE_KEYS = {
token: 'token',
} as const;

export { STORAGE_KEYS };
26 changes: 26 additions & 0 deletions src/utils/localStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { STORAGE_KEYS } from '@constants/storageKeys';

type StorageKeys = keyof typeof STORAGE_KEYS;

const setStorage = <T>(key: StorageKeys, value: T) => {
try {
const jsonValue = JSON.stringify(value);
localStorage.setItem(key, jsonValue);
} catch {
throw new Error('로컬 스토리지에 값을 저장하는 도중 오류가 발생했습니다.');
}
};

const getStorage = <T>(key: StorageKeys, defaultValue?: unknown): T => {
const jsonValue = localStorage.getItem(key);
if (!jsonValue && !defaultValue) {
throw new Error('로컬 스토리지에 존재하지 않는 값입니다.');
}
return jsonValue ? JSON.parse(jsonValue) : defaultValue;
};

const deleteStorage = (key: StorageKeys) => {
localStorage.removeItem(key);
};

export { getStorage, setStorage, deleteStorage };

0 comments on commit 0edaa9c

Please sign in to comment.