-
Notifications
You must be signed in to change notification settings - Fork 6
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-fe: useLocalStorageState 구현 #964
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
86be480
Create draft PR for #963
github-actions[bot] 21ba4f9
test: useLocalStorageState 테스트 코드 작성
lurgi 3b0dfdb
feat: useLocalStorageState hook 구현
lurgi c709bcd
test: useLocalStorageState 테스트 케이스 추가
lurgi cad5367
refactor: setState 인자 값 명시적으로 변환
lurgi f9b52cd
test: 컴포넌트 테스트 훅 테스트로 변경
lurgi f947811
test: enableStorage옵션 추가
lurgi 60c5c6d
feat: enableStorage 옵션 추가
lurgi e7956f2
refactor: useLocalStorageState 코드 개선
lurgi 938a837
chore: useLocalStorageState의 Prop 개선
lurgi f0fdad7
refactor: 에러 핸들링 개선
lurgi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,61 @@ | ||
import { useState } from 'react'; | ||
|
||
interface OptionProp { | ||
key: string; | ||
enableStorage?: boolean; | ||
} | ||
|
||
const safeParseJSON = <T>(value: string | null, fallback: T): T => { | ||
try { | ||
return value !== null ? JSON.parse(value) : fallback; | ||
} catch (error) { | ||
if (process.env.NODE_ENV === 'development') { | ||
console.error('JSON 파싱 실패:', error); | ||
} | ||
return fallback; | ||
} | ||
}; | ||
|
||
const safeStringifyJSON = <T>(value: T): string | null => { | ||
try { | ||
return JSON.stringify(value); | ||
} catch (error) { | ||
if (process.env.NODE_ENV === 'development') { | ||
console.error('JSON 직렬화 실패:', error); | ||
} | ||
return null; | ||
} | ||
}; | ||
|
||
/** | ||
* useLocalStorageState | ||
* @param initialValue - 초기 상태 값 | ||
* @param option - { key: LocalStorage에 저장될 키 값, enableStorage: LocalStorage의 값을 사용할지 여부} | ||
* @returns [상태 값, 상태를 변경하는 함수] useState의 반환값과 동일합니다. | ||
*/ | ||
function useLocalStorageState<T>(initialValue: T, option: OptionProp): [T, (value: T | ((prev: T) => T)) => void] { | ||
const { key, enableStorage = true } = option; | ||
|
||
const [state, _setState] = useState<T>(() => { | ||
if (!enableStorage) return initialValue; | ||
|
||
const storedValue = window.localStorage.getItem(key); | ||
return safeParseJSON(storedValue, initialValue); | ||
}); | ||
|
||
const saveToLocalStorage = (value: T) => { | ||
const stringifiedValue = safeStringifyJSON(value); | ||
if (stringifiedValue !== null) { | ||
window.localStorage.setItem(key, stringifiedValue); | ||
} | ||
}; | ||
|
||
const setState = (value: T | ((prev: T) => T)) => { | ||
_setState(value); | ||
saveToLocalStorage(value instanceof Function ? value(state) : value); | ||
}; | ||
|
||
return [state, setState]; | ||
} | ||
|
||
export default useLocalStorageState; |
122 changes: 122 additions & 0 deletions
122
frontend/src/hooks/useLocalStorageState/useLocalStorageState.test.tsx
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,122 @@ | ||
/* eslint-disable function-paren-newline */ | ||
import { act } from 'react'; | ||
import { renderHook } from '@testing-library/react'; | ||
import useLocalStorageState from '.'; | ||
|
||
describe('useLocalStorageState의 값이 원시값인 경우에 대한 테스트', () => { | ||
beforeEach(() => { | ||
window.localStorage.clear(); | ||
}); | ||
|
||
describe('Primitive Value Tests', () => { | ||
it('초기 상태를 설정한다', () => { | ||
const { result } = renderHook(() => useLocalStorageState(0, { key: 'primitiveKey' })); | ||
expect(result.current[0]).toBe(0); | ||
}); | ||
|
||
it('[setState 인자 원시값] 상태 변경 시 localStorage에 저장한다', () => { | ||
const { result } = renderHook(() => useLocalStorageState(0, { key: 'primitiveKey' })); | ||
|
||
act(() => { | ||
result.current[1]((prev) => prev + 1); | ||
}); | ||
|
||
expect(result.current[0]).toBe(1); | ||
expect(window.localStorage.getItem('primitiveKey')).toBe('1'); | ||
}); | ||
|
||
it('[setState 인자 함수] 상태 변경 시 localStorage에 저장한다', () => { | ||
const { result } = renderHook(() => useLocalStorageState(0, { key: 'primitiveKey' })); | ||
|
||
act(() => { | ||
result.current[1]((prev) => prev + 1); | ||
}); | ||
|
||
expect(result.current[0]).toBe(1); | ||
expect(window.localStorage.getItem('primitiveKey')).toBe('1'); | ||
}); | ||
|
||
it('localStorage에 값이 있으면 초기 상태로 사용한다', () => { | ||
window.localStorage.setItem('primitiveKey', '10'); | ||
|
||
const { result } = renderHook(() => useLocalStorageState(0, { key: 'primitiveKey' })); | ||
expect(result.current[0]).toBe(10); | ||
|
||
act(() => { | ||
result.current[1]((prev) => prev + 1); | ||
}); | ||
|
||
expect(result.current[0]).toBe(11); | ||
expect(window.localStorage.getItem('primitiveKey')).toBe('11'); | ||
}); | ||
|
||
it('enableStorage 옵션을 false로 지정한 경우 localStorage를 사용하지 않는다', () => { | ||
window.localStorage.setItem('primitiveKey', '10'); | ||
|
||
const { result } = renderHook(() => useLocalStorageState(0, { key: 'primitiveKey', enableStorage: false })); | ||
|
||
expect(result.current[0]).toBe(0); | ||
expect(window.localStorage.getItem('primitiveKey')).toBe('10'); | ||
}); | ||
}); | ||
|
||
describe('useLocalStorageState의 값이 객체인 경우에 대한 테스트', () => { | ||
it('초기 상태를 설정한다', () => { | ||
const initialObject = { name: 'lurgi', age: 30 }; | ||
const { result } = renderHook(() => useLocalStorageState(initialObject, { key: 'objectKey' })); | ||
expect(result.current[0]).toEqual(initialObject); | ||
}); | ||
|
||
it('[setState 인자 원시값] 상태 변경 시 localStorage에 저장한다', () => { | ||
const initialObject = { name: 'lurgi', age: 30 }; | ||
const { result } = renderHook(() => useLocalStorageState(initialObject, { key: 'objectKey' })); | ||
|
||
act(() => { | ||
result.current[1]({ name: 'lurgi', age: 31 }); | ||
}); | ||
|
||
expect(result.current[0]).toEqual({ name: 'lurgi', age: 31 }); | ||
expect(window.localStorage.getItem('objectKey')).toBe(JSON.stringify({ name: 'lurgi', age: 31 })); | ||
}); | ||
|
||
it('[setState 인자 함수] 상태 변경 시 localStorage에 저장한다', () => { | ||
const initialObject = { name: 'lurgi', age: 30 }; | ||
const { result } = renderHook(() => useLocalStorageState(initialObject, { key: 'objectKey' })); | ||
|
||
act(() => { | ||
result.current[1]((prev) => ({ ...prev, age: prev.age + 1 })); | ||
}); | ||
|
||
expect(result.current[0]).toEqual({ name: 'lurgi', age: 31 }); | ||
expect(window.localStorage.getItem('objectKey')).toBe(JSON.stringify({ name: 'lurgi', age: 31 })); | ||
}); | ||
|
||
it('localStorage에 값이 있으면 초기 상태로 사용한다', () => { | ||
const storedObject = JSON.stringify({ name: 'jeong woo', age: 28 }); | ||
window.localStorage.setItem('objectKey', storedObject); | ||
|
||
const { result } = renderHook(() => useLocalStorageState({ name: 'default', age: 0 }, { key: 'objectKey' })); | ||
expect(result.current[0]).toEqual({ name: 'jeong woo', age: 28 }); | ||
|
||
act(() => { | ||
result.current[1]((prev) => ({ ...prev, age: prev.age + 1 })); | ||
}); | ||
|
||
expect(result.current[0]).toEqual({ name: 'jeong woo', age: 29 }); | ||
expect(window.localStorage.getItem('objectKey')).toBe(JSON.stringify({ name: 'jeong woo', age: 29 })); | ||
}); | ||
|
||
it('enableStorage 옵션을 false로 지정한 경우 localStorage를 사용하지 않는다', () => { | ||
const storedObject = JSON.stringify({ name: 'jeong woo', age: 28 }); | ||
window.localStorage.setItem('objectKey', storedObject); | ||
|
||
const initialObject = { name: 'lurgi', age: 30 }; | ||
const { result } = renderHook(() => | ||
useLocalStorageState(initialObject, { key: 'objectKey', enableStorage: false }), | ||
); | ||
|
||
expect(result.current[0]).toEqual(initialObject); | ||
expect(window.localStorage.getItem('objectKey')).toBe(storedObject); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
parsing, stringify 로직을 깔끔하게 분리해주셨네요 👍