I watched a tutorial, where I was told that I should use async methods to access localStorage (in an Ionic Angular project, don't know if this is important or if it affects the programm if I export it as an mobile application with capacitor)
I have this example:
async store(storageKey: string, value: any) {
const encryptedValue = btoa(escape(JSON.stringify(value)));
await Storage.set({
key: storageKey,
value: encryptedValue
});
}
but isn't that the same as just
store(storageKey: string, value: any) {
const encryptedValue = btoa(escape(JSON.stringify(value)));
localStorage.setItem(storageKey, encryptedValue);
}
Is there a reason for using the more complicate async-method? Because working with it is really annoying.
EDIT: The Storage is a capacitor plugin:
import { Plugins } from '@capacitor/core'
const { Storage } = Plugins;
That also converts the code to use it on mobile devices that use different storage-Systems. Thats what the capacitor docs say:
The Storage API provides a key-value store for simple data. Mobile OS's may periodically clear data set in window.localStorage, so this API should be used instead of window.localStorage. This API will fall back to using localStorage when running as a Progressive Web App. On iOS this plugin will use UserDefaults and on Android SharedPreferences. Stored data is cleared if the app is uninstalled.
https://capacitorjs.com/docs/apis/storage
Probably you need async methods because of that.
Continuing question: I need data from one of those async methods and I always had the problem with an error because the data has not loaded so far. Due to some experimenting I found this solution:
ngOnInit() {
console.log("ONINIT IS CALLED");
this.authService.userData$.subscribe(
res => {
console.log(res);
if(!res) {
return;
}
const payload = atob(res.split(".")[1]);
const parsed_payload = JSON.parse(payload);
const userID = parsed_payload.subject;
this.catchService.get_catches(userID).subscribe(
res => {
this.catches = res;
console.log(this.catches);
},
err => {
this.toastService.presentToast('Fänge konnten nicht geladen werden.')
}
)
},
err => {
this.toastService.presentToast('Fänge konnten nicht geladen werden, userID konnte nicht geladen werden.');
}
)
}
If I leave out the
if(!res) {
return;
}
it does not work, so my question is: What does this 'return' does. I always thought that a method would terminate if there is a return-statement. But if I look at the outputs i get this sequence:
console.log("ONINIT IS CALLED");
console.log(res); (That is an empty String)
console.log(res); (That is the value I need)
console.log(this.catches); (My data)