-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat : 스토리지 키 상수 저장 * feat : 로컬스토리지 관련 함수 추가 * fix : localStorage 에러 상황 변경
- Loading branch information
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const STORAGE_KEYS = { | ||
token: 'token', | ||
} as const; | ||
|
||
export { STORAGE_KEYS }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |