Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created February 20, 2021 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgornick/e9fb5f3cafa63914fa19c936e89a98ed to your computer and use it in GitHub Desktop.
Save jgornick/e9fb5f3cafa63914fa19c936e89a98ed to your computer and use it in GitHub Desktop.
React Native: Async Storage Hook
/* 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