Last active
October 8, 2024 19:13
-
-
Save EduVencovsky/dbaff299f7de6fe94538086c137f21d3 to your computer and use it in GitHub Desktop.
React Native hook for keeping the state in sync with AsyncStorage
This file contains 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
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