Reputation: 2156
Is there a way to subscribe to an AsyncStorage
value changes? I have a setting in one place which is saved in AsyncStorage
in an app, which affects every other screen. I need to observe the value so that it is possible to update all the screens. I tried the getValue
method but it seems to only get a value initially, and does not update on a change.
Upvotes: 7
Views: 8060
Reputation: 2566
I solved this issue in my app by building a React Context that synced to AsyncStorage.
In your case, you could have one item called for example appSettings
. This would be a stringified JSON object that holds all of your app settings.
const AppSettingsContext = React.createContext({})
const AppSettingsContextProvider = ({children}) => {
const [appSettingsInitialized, setAppSettingsInitialized] = useState(false)
const [appSettings, setAppSettings] = useState({}) // could use some default values instead of empty object
// On mount, get the current value of `appSettings` in AsyncStorage
useEffect(() => {
AsyncStorage
.getItem('appSettings')
.then(data => {
// If data is returned, the storage item existed already and we set the appSettings state to that.
if (data) {
setAppSettings(JSON.parse(data))
}
// If data is null, the appSettings keeps the default value (in this case an empty object)/
// We set appSettingsInitialized to true to signal that we have successfully retrieved the initial values.
setAppSettingsInitialized(true)
})
}, [])
// setSettings sets the local state and AsyncStorage
const setSettings = (key, value) => {
const mergedSettings = {
...appSettings,
[key]: value
}
// First, merge the current state with the new value
setAppSettings(mergedSettings)
// Then update the AsyncStorage item
AsyncStorage.setItem('appSettings', JSON.stringify(mergedSettings))
}
return (
<AppSettingsContext.Provider value={{
appSettings,
appSettingsInitialized,
setSettings,
}}>
{children}
</AppSettingsContext.Provider>
)
}
(note that this is a pretty basic version, with no error handling)
Then wrap you app in AppSettingsContextProvider
const App = () => (
<AppSettingsContextProvider>
{/* Other components */}
</AppSettingsContextProvider>
)
Then consume the context from any child component:
const SomeChildComponent = () => {
const { appSettingsInitialized, appSettings } = useContext(AppSettingsContext)
// For example: wait until initial appSettings have been retrieved AsyncStorage,
// then use some value that you expect to be present in your business logic.
// In this case, setAppTheme would set the them color for the whole app, using a
// `theme` setting saved by the user.
useEffect(() => {
if (appSettingsInitialized) {
setAppTheme(appSettings.theme)
}
}, [appSettingsInitialized])
// Update settings like this for example
const updateThemeSetting = (newThemeValue) => {
setSettings('theme', newThemeValue) // eg 'dark', 'light', etc
}
}
Upvotes: 4
Reputation: 121
Of course, if you use react-native-easy-app to help you use AsyncStorage, you can get two benefits through react-native-easy-app,
First: You can access AsyncStorage synchronously and quickly, and support direct access to data such as strings, Booleans, objects, arrays, etc. code snippets
Second: When you modify any AsyncStorage data, there will be a callback function to tell you the corresponding data changes. code snippets
For details, please refer to the sample project
You can use it as follows:
import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';
// or import AsyncStorage from '@react-native-community/async-storage';
export const RNStorage = {
token: undefined,
isShow: undefined,
userInfo: undefined
};
const initCallback = () => {
// From now on, you can write or read the variables in RNStorage synchronously
// equal to [console.log(await AsyncStorage.getItem('isShow'))]
console.log(RNStorage.isShow);
// equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]
RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3==';
// equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
RNStorage.userInfo = {name: 'rufeng', age: 30};
};
const dataSetChangedCallback = (data) => {
data.map(([keyStr, value]) => {
let [, key] = keyStr.split('#');
console.log('data has changed:', key, '<###>', value);
})
};
XStorage.initStorage(RNStorage, AsyncStorage, initCallback, dataSetChangedCallback);
Upvotes: 0
Reputation: 35
You can use the AsyncStorage.getItem()
in a useEffect to watch the value right after your component mounts.
useEffect(() => {
(async () => {
console.log(await AsyncStorage.getItem('YOUR_ITEM_KEY'));
})();
}, []);
with this syntax you can log the item with the key "YOUR_ITEM_KEY".
If you are using a class component you can do it like this:
show = async () => {
console.log(await AsyncStorage.getItem('YOUR_ITEM_KEY'));
}
componentDidMount(){
this.show();
}
Upvotes: -2