From 0edaa9c9f419f1703df0e53ed0101e334ba7f056 Mon Sep 17 00:00:00 2001 From: hyesung99 <4538asd@gmail.com> Date: Wed, 25 Oct 2023 17:13:26 +0900 Subject: [PATCH] =?UTF-8?q?SKRF-146=20local=20storage=20=EA=B8=B0=EB=8A=A5?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80=20(#21)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat : 스토리지 키 상수 저장 * feat : 로컬스토리지 관련 함수 추가 * fix : localStorage 에러 상황 변경 --- src/constants/storageKeys.ts | 5 +++++ src/utils/localStorage.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/constants/storageKeys.ts create mode 100644 src/utils/localStorage.ts diff --git a/src/constants/storageKeys.ts b/src/constants/storageKeys.ts new file mode 100644 index 00000000..abb7dd85 --- /dev/null +++ b/src/constants/storageKeys.ts @@ -0,0 +1,5 @@ +const STORAGE_KEYS = { + token: 'token', +} as const; + +export { STORAGE_KEYS }; diff --git a/src/utils/localStorage.ts b/src/utils/localStorage.ts new file mode 100644 index 00000000..53fc9e3d --- /dev/null +++ b/src/utils/localStorage.ts @@ -0,0 +1,26 @@ +import { STORAGE_KEYS } from '@constants/storageKeys'; + +type StorageKeys = keyof typeof STORAGE_KEYS; + +const setStorage = (key: StorageKeys, value: T) => { + try { + const jsonValue = JSON.stringify(value); + localStorage.setItem(key, jsonValue); + } catch { + throw new Error('로컬 스토리지에 값을 저장하는 도중 오류가 발생했습니다.'); + } +}; + +const getStorage = (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 };