|
|
|
|
@ -38,11 +38,13 @@ const createHook = (storage: Storage) => ( |
|
|
|
|
key, |
|
|
|
|
validator = defaultValidator, |
|
|
|
|
}: Args<T>) => { |
|
|
|
|
const storeValue = readStorageInitialValue(storage, key) |
|
|
|
|
const isValid = validator(storeValue) |
|
|
|
|
const initialState = isValid ? storeValue : defaultValue |
|
|
|
|
const getInitialState = () => { |
|
|
|
|
const storeValue = readStorageInitialValue(storage, key) |
|
|
|
|
const isValid = validator(storeValue) |
|
|
|
|
return isValid ? storeValue : defaultValue |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
const [state, setState] = useState<T>(initialState) |
|
|
|
|
const [state, setState] = useState<T>(getInitialState) |
|
|
|
|
|
|
|
|
|
const setStateAndSave = useCallback((value: T) => { |
|
|
|
|
storage.setItem(key, JSON.stringify(value, dateReplacer)) |
|
|
|
|
@ -50,10 +52,12 @@ const createHook = (storage: Storage) => ( |
|
|
|
|
}, [key]) |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
const storeValue = readStorageInitialValue(storage, key) |
|
|
|
|
const isValid = validator(storeValue) |
|
|
|
|
if (!isValid) { |
|
|
|
|
storage.removeItem(key) |
|
|
|
|
} |
|
|
|
|
}, [isValid, key]) |
|
|
|
|
}, [key, validator]) |
|
|
|
|
|
|
|
|
|
return [state, setStateAndSave] as const |
|
|
|
|
} |
|
|
|
|
|