Created
February 20, 2021 14:51
-
-
Save jgornick/e9fb5f3cafa63914fa19c936e89a98ed to your computer and use it in GitHub Desktop.
React Native: Async Storage Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-unused-vars */ | |
import { useEffect, useState } from 'react' | |
import AsyncStorage from '@react-native-community/async-storage' | |
import { isNil } from 'lodash'; | |
export const useAsyncStorage = | |
<TValue = any>(key: string, defaultValue?: TValue): | |
[TValue | undefined, typeof setValue, boolean] => | |
{ | |
const [value, setLocalValue] = useState<TValue | undefined>(defaultValue); | |
const [isLoading, setIsLoading] = useState(true); | |
const setValue = async (value: TValue) => { | |
setIsLoading(true) | |
await AsyncStorage.setItem(key, JSON.stringify(value)) | |
setLocalValue(value) | |
setIsLoading(false) | |
} | |
useEffect(() => { | |
const getValue = async () => { | |
try { | |
setIsLoading(true) | |
const value = await AsyncStorage.getItem(key) | |
if (value === null && !isNil(defaultValue)) { | |
return setValue(defaultValue) | |
} | |
if (value !== null) { | |
setLocalValue(JSON.parse(value)) | |
} | |
} catch (e) { | |
if (!isNil(defaultValue)) { | |
setValue(defaultValue) | |
} | |
} finally { | |
setIsLoading(false) | |
} | |
} | |
getValue() | |
}, []) | |
return [value, setValue, isLoading] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment