Skip to content

Instantly share code, notes, and snippets.

@EduVencovsky
Last active October 8, 2024 19:13
Show Gist options
  • Save EduVencovsky/dbaff299f7de6fe94538086c137f21d3 to your computer and use it in GitHub Desktop.
Save EduVencovsky/dbaff299f7de6fe94538086c137f21d3 to your computer and use it in GitHub Desktop.
React Native hook for keeping the state in sync with AsyncStorage
import { useState, useEffect } from 'react'
import AsyncStorage from '@react-native-community/async-storage'
const useAsyncStorage = (key, initialValue) => {
const [hasLoad, setHasLoad] = useState(false)
const [data, setData] = useState(initialValue)
const set = async newData => {
setData(newData)
return newData === null ?
AsyncStorage.removeItem(key) :
AsyncStorage.setItem(key, JSON.stringify(newData))
}
useEffect(() => {
setHasLoad(false)
}, [key])
useEffect(() => {
if (!hasLoad) {
AsyncStorage.getItem(key)
.then(res => {
if (res === null) {
AsyncStorage.setItem(
key,
JSON.stringify(data),
)
setData(data)
} else {
setData(JSON.parse(res))
}
setHasLoad(true)
})
}
}, [key, hasLoad, data])
return [data, set]
}
export default useStorage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment