Skip to content

Instantly share code, notes, and snippets.

@djdam
Last active January 12, 2022 23:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djdam/1dd3d0a1023a6533419aa4ec01ff7463 to your computer and use it in GitHub Desktop.
Save djdam/1dd3d0a1023a6533419aa4ec01ff7463 to your computer and use it in GitHub Desktop.
LocalForageStorage
import localforage from 'localforage';
import { Auth } from 'aws-amplify';
export class LocalForageStorage {
syncPromise = null;
memoryStore = {};
asyncStore = localforage.createInstance({
name: 'amplifyStore'
});
setItem(key: string, value: any) {
this.asyncStore.setItem(key, value);
this.memoryStore[key] = value;
return this.memoryStore[key];
}
getItem(key: string) {
return Object.prototype.hasOwnProperty.call(this.memoryStore, key) ? this.memoryStore[key] : undefined;
}
removeItem(key: string) {
this.asyncStore.removeItem(key);
return delete this.memoryStore[key];
}
clear() {
this.asyncStore.clear();
return {};
}
sync(): Promise<void> {
if (!this.syncPromise) {
this.syncPromise = this.asyncStore.iterate((val: string, key) => {
this.memoryStore[key] = val;
});
}
return this.syncPromise;
}
}
Auth.configure({
storage: new LocalForageStorage()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment