mirror of
https://github.com/CompassConnections/Compass.git
synced 2025-12-23 22:18:43 -05:00
34 lines
1.3 KiB
TypeScript
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
|
|
}
|