As in web storage, it would be very useful to have { onChange } listener that will trigger each time values in storage changed. That way different components can be rendered with new values, even if the change happened somewhere else
IMO, this would go beyond the scope of this package. Adding reactive functionality could be done in local codebase, with some abstraction on top of Async Storage.
I agree it possible to achieve it as you said with some abstraction on top of Async Storage, but IMO it is a bit shame that this great package has a big downside e without state management, and even with, it not following DRY standard to have the same constant in both AsyncStorage and store, when you can have only in AsyncStorage in case event listener exist
@YogiHa did you find a way to implement an event wrapper on top of async-storage?
@Krizzu, there's this case where we have an auth token;
if the token is removed, then we have to redirect the user to login;
another argument is that web localstorage have such a thing
@cmnstmntmn I have also redux store, and actually the variable live there. Any time redux action change the state I also set the asyncStore state.
At init mount I set initial redux state as the cached value if exist
it not following DRY standard to have the same constant in both AsyncStorage and store, when you can have only in AsyncStorage in case event listener exist
@YogiHa It's more about separation of domains here - one is persistent storage, one is a state management.
@cmnstmntmn
For example, you could use a facade pattern for reading/saving persisting data and add listener functionality on top of that.
class Storage {
_enableFlag: boolean = false;
_listeners = [];
constructor() {
AsyncStorage.getItem('flag').then(value => {
this._enableFlag = value;
});
}
addListener(listener: () => void) {
this._listeners.push(listener);
}
readFlag = () => this._enableFlag;
saveFlag(value: boolean) {
AsyncStorage.setItem('flag', value).then(() => {
this._enableFlag = value;
this._listeners.forEach(listener => listener(value));
});
}
}
export default new Storage();
While I also was just missing this listener functionality I can understand the decission not to include this. The code example from @Krizzu would be a good candidate for a react-native-async-storage-listener package ;)