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

Feat: Add setItemIfNotExists option to set storage value if not exists #532

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
30 changes: 30 additions & 0 deletions packages/usehooks-ts/src/useLocalStorage/useLocalStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,4 +235,34 @@ describe('useLocalStorage()', () => {

expect(localStorage.getItem('key')).toBe('42')
})

it('should set local storage value to initial if not exists and `setItemIfNotExists` is true', () => {
const LOCAL_STORAGE_KEY = 'key'
const INITIAL_VALUE = 'initial_value'
expect(localStorage.getItem(LOCAL_STORAGE_KEY)).toBeNull()

renderHook(() =>
useLocalStorage(LOCAL_STORAGE_KEY, INITIAL_VALUE, {
setItemIfNotExists: true,
}),
)

expect(localStorage.getItem(LOCAL_STORAGE_KEY)).toBe(
JSON.stringify(INITIAL_VALUE),
)
})

it('should not set local storage value to initial if not exists and `setItemIfNotExists` is false', () => {
const LOCAL_STORAGE_KEY = 'key'
const INITIAL_VALUE = 'initial_value'
expect(localStorage.getItem(LOCAL_STORAGE_KEY)).toBeNull()

renderHook(() =>
useLocalStorage(LOCAL_STORAGE_KEY, INITIAL_VALUE, {
setItemIfNotExists: false,
}),
)

expect(localStorage.getItem(LOCAL_STORAGE_KEY)).toBeNull()
})
})
17 changes: 17 additions & 0 deletions packages/usehooks-ts/src/useLocalStorage/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ type UseLocalStorageOptions<T> = {
* @default true
*/
initializeWithValue?: boolean
/**
* If `true`, the hook will initialize local storage value if it not exists.
*/
setItemIfNotExists?: boolean
}

const IS_SERVER = typeof window === 'undefined'
Expand Down Expand Up @@ -145,6 +149,19 @@ export function useLocalStorage<T>(
})

useEffect(() => {
if (options.setItemIfNotExists) {
try {
const localStorageValue = window.localStorage.getItem(key)
if (localStorageValue === null) {
const initialValueToUse =
initialValue instanceof Function ? initialValue() : initialValue
window.localStorage.setItem(key, serializer(initialValueToUse))
}
} catch (error) {
console.warn(`Error initializing localStorage key “${key}”:`, error)
}
}

setStoredValue(readValue())
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,34 @@ describe('useSessionStorage()', () => {

expect(sessionStorage.getItem('key')).toBe('42')
})

it('should set session storage value to initial if not exists and `setItemIfNotExists` is true', () => {
const SESSION_STORAGE_KEY = 'key'
const INITIAL_VALUE = 'initial_value'
expect(sessionStorage.getItem(SESSION_STORAGE_KEY)).toBeNull()

renderHook(() =>
useSessionStorage(SESSION_STORAGE_KEY, INITIAL_VALUE, {
setItemIfNotExists: true,
}),
)

expect(sessionStorage.getItem(SESSION_STORAGE_KEY)).toBe(
JSON.stringify(INITIAL_VALUE),
)
})

it('should not set session storage value to initial if not exists and `setItemIfNotExists` is false', () => {
const SESSION_STORAGE_KEY = 'key'
const INITIAL_VALUE = 'initial_value'
expect(sessionStorage.getItem(SESSION_STORAGE_KEY)).toBeNull()

renderHook(() =>
useSessionStorage(SESSION_STORAGE_KEY, INITIAL_VALUE, {
setItemIfNotExists: false,
}),
)

expect(sessionStorage.getItem(SESSION_STORAGE_KEY)).toBeNull()
})
})
17 changes: 17 additions & 0 deletions packages/usehooks-ts/src/useSessionStorage/useSessionStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ type UseSessionStorageOptions<T> = {
* @default true
*/
initializeWithValue?: boolean
/**
* If `true`, the hook will initialize session storage value if it not exists.
*/
setItemIfNotExists?: boolean
}

const IS_SERVER = typeof window === 'undefined'
Expand Down Expand Up @@ -146,6 +150,19 @@ export function useSessionStorage<T>(
})

useEffect(() => {
if (options.setItemIfNotExists) {
try {
const sessionStorageValue = window.sessionStorage.getItem(key)
if (sessionStorageValue === null) {
const initialValueToUse =
initialValue instanceof Function ? initialValue() : initialValue
window.sessionStorage.setItem(key, serializer(initialValueToUse))
}
} catch (error) {
console.warn(`Error initializing sessionStorage key “${key}”:`, error)
}
}

setStoredValue(readValue())
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key])
Expand Down