Files
Compass/web/hooks/use-persistent-local-state.ts
Martin Braquet ba9b3cfb06 Add pretty formatting (#29)
* Test

* Add pretty formatting

* Fix Tests

* Fix Tests

* Fix Tests

* Fix

* Add pretty formatting fix

* Fix

* Test

* Fix tests

* Clean typeckech

* Add prettier check

* Fix api tsconfig

* Fix api tsconfig

* Fix tsconfig

* Fix

* Fix

* Prettier
2026-02-20 17:32:27 +01:00

34 lines
1.3 KiB
TypeScript

import {safeJsonParse} from 'common/util/json'
import {useEffect} from 'react'
import {safeLocalStorage} from 'web/lib/util/local'
import {isFunction} from 'web/hooks/use-persistent-in-memory-state'
import {useStateCheckEquality} from 'web/hooks/use-state-check-equality'
import {useEvent} from 'web/hooks/use-event'
import {useIsClient} from 'web/hooks/use-is-client'
export const usePersistentLocalState = <T>(initialValue: T, key: string) => {
// Note: use a version (like "-v1") in the key to increment after backwards-incompatible changes
const isClient = useIsClient()
const [state, setState] = useStateCheckEquality<T>(
(isClient && safeJsonParse(safeLocalStorage?.getItem(key))) || initialValue,
)
const saveState = useEvent((newState: T | ((prevState: T) => T)) => {
setState((prevState: T) => {
const updatedState = isFunction(newState) ? newState(prevState) : newState
safeLocalStorage?.setItem(key, JSON.stringify(updatedState))
return updatedState
})
})
useEffect(() => {
if (safeLocalStorage) {
const storedJson = safeJsonParse(safeLocalStorage.getItem(key))
const storedValue = storedJson ?? initialValue
if (storedJson === null && initialValue === undefined) return
saveState(storedValue as T)
}
}, [key])
return [state, saveState] as const
}