Skip to content
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

feature: add a reset function to useLocalStorage #487

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useLocalStorage } from './useLocalStorage'

export default function Component() {
const [value, setValue] = useLocalStorage('test-key', 0)
const [value, setValue, reset] = useLocalStorage('test-key', 0)

return (
<div>
Expand All @@ -20,6 +20,13 @@ export default function Component() {
>
Decrement
</button>
<button
onClick={() => {
reset()
}}
>
Reset
</button>
</div>
)
}
43 changes: 43 additions & 0 deletions packages/usehooks-ts/src/useLocalStorage/useLocalStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,49 @@ describe('useLocalStorage()', () => {
expect(window.localStorage.getItem('count')).toEqual('5')
})

it('Reset the state with static initial value', () => {
const { result } = renderHook(() => useLocalStorage('count', 2))

act(() => {
const setState = result.current[1]
const reset = result.current[2]
setState(prev => prev + 1)
setState(prev => prev + 1)
setState(prev => prev + 1)
reset()
})

expect(result.current[0]).toBe(2)
expect(window.localStorage.getItem('count')).toEqual('2')
})

it('Reset the state with initial value as a function', () => {
const { result } = renderHook(() =>
useLocalStorage('count', () => ({
id: 1,
name: 'Joe',
})),
)

act(() => {
const setState = result.current[1]
const reset = result.current[2]
setState({
id: 2,
name: 'Jane',
})
reset()
})

expect(result.current[0]).toEqual({
id: 1,
name: 'Joe',
})
expect(window.localStorage.getItem('count')).toEqual(
'{"id":1,"name":"Joe"}',
)
})

it('[Event] Update one hook updates the others', () => {
const initialValues: [string, unknown] = ['key', 'initial']
const { result: A } = renderHook(() => useLocalStorage(...initialValues))
Expand Down
17 changes: 14 additions & 3 deletions packages/usehooks-ts/src/useLocalStorage/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const IS_SERVER = typeof window === 'undefined'
* @param {?boolean} [options.initializeWithValue] - If `true` (default), the hook will initialize reading the local storage. In SSR, you should set it to `false`, returning the initial value initially.
* @param {?((value: T) => string)} [options.serializer] - A function to serialize the value before storing it.
* @param {?((value: string) => T)} [options.deserializer] - A function to deserialize the stored value.
* @returns {[T, Dispatch<SetStateAction<T>>]} A tuple containing the stored value and a function to set the value.
* @returns {[T, Dispatch<SetStateAction<T>>, () => void]} A tuple containing the stored value and a function to set the value.
* @see [Documentation](https://usehooks-ts.com/react-hook/use-local-storage)
* @see [MDN Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
* @example
Expand All @@ -39,7 +39,7 @@ export function useLocalStorage<T>(
key: string,
initialValue: T | (() => T),
options: UseLocalStorageOptions<T> = {},
): [T, Dispatch<SetStateAction<T>>] {
): [T, Dispatch<SetStateAction<T>>, () => void] {
const { initializeWithValue = true } = options

const serializer = useCallback<(value: T) => string>(
Expand Down Expand Up @@ -133,6 +133,17 @@ export function useLocalStorage<T>(
}
})

const resetValue = useCallback(() => {
try {
const initialValueToUse =
initialValue instanceof Function ? initialValue() : initialValue

setValue(initialValueToUse)
} catch (error) {
console.warn(`Error resetting localStorage key “${key}”:`, error)
}
}, [initialValue, setValue, key])

useEffect(() => {
setStoredValue(readValue())
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -155,5 +166,5 @@ export function useLocalStorage<T>(
// See: useLocalStorage()
useEventListener('local-storage', handleStorageChange)

return [storedValue, setValue]
return [storedValue, setValue, resetValue]
}