As we know, we cannot use LocalStorage in React Native. I try to create a useAsyncStorage custom hook instead, which do same function as LocalStorage custome hook in react to store the data in mobile device's local storage.
useAsyncStorage.js
import React, { useEffect, useState } from 'react';
import AsyncStorage from '@react-native-community/async-storage';
export default function useAsyncStorage(key, defaultValue) {
const [storageValue, updateStorageValue] = useState(defaultValue);
useEffect(() => {
getStorageValue();
}, []);
async function getStorageValue() {
let value = defaultValue;
try {
value = (JSON.parse(await AsyncStorage.getItem(key))) || defaultValue;
} catch (e) {
// handle here
} finally {
updateStorage(value);
}
}
async function updateStorage(newValue) {
try {
await AsyncStorage.setItem(key, JSON.stringify(newValue));
} catch (e) {
// handle here
} finally {
getStorageValue();
}
}
return [storageValue, updateStorageValue];
}
In App.js I import useAsyncStorage.js and try use it to store the data in mobile device's local storage.
import useAsyncStorage from './useAsyncStorage';
To initial it:
const [userLevel, setUserLevel] = useAsyncStorage("userLevel",1)
To setValue:
setUserLevel(prevLevel => {
return prevLevel + 1
})
It works as expected and set the data, but it cannot retrieve data from AsyncStorage after app reload.
Could anyone please help? Did I do something wrong in useAsyncStorage custom hook? Why data don't store in AsyncStorage?