Skip to content

Commit

Permalink
fix(js-core): no longer throw error when localStorage is not available
Browse files Browse the repository at this point in the history
Closes #17
  • Loading branch information
ersimont committed Jan 7, 2021
1 parent 2b68dff commit 06be1e5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
18 changes: 17 additions & 1 deletion projects/js-core/src/lib/persistence.spec.ts
Expand Up @@ -6,7 +6,7 @@ describe('Persistence', () => {
localStorage.removeItem(key);
});
afterEach(() => {
localStorage.removeItem(key);
localStorage?.removeItem(key);
});

it('works for the example in the docs', () => {
Expand All @@ -21,6 +21,22 @@ describe('Persistence', () => {
expect(persistence.get()).toEqual({ name: 'Robert' });
});

// this can happen in android webviews, where it's up to the embedding app to call `.setDomStorageEnabled()`
it('gracefully handles when localStorage is null', () => {
spyOnProperty(window, 'localStorage').and.returnValue(null);
const persistence = new Persistence('my key');

expect(() => {
persistence.put('ignored');
}).not.toThrowError();

expect(persistence.get()).toBeUndefined();

expect(() => {
persistence.clear();
}).not.toThrowError();
});

describe('.put() & .get()', () => {
it('can work with primitives', () => {
const value = 42;
Expand Down
10 changes: 6 additions & 4 deletions projects/js-core/src/lib/persistence.ts
@@ -1,6 +1,8 @@
/**
* Get and put objects from/to local storage. They will be (de)serialized as JSON, so be sure that's OK for your objects.
*
* If localStorage is not available, all methods essentially act as noops.
*
* ```ts
* // if 'my key' has never been used before
* const persistence = new Persistence('my key');
Expand All @@ -23,21 +25,21 @@ export class Persistence<T> {
* Serializes `obj` and saves it in local storage.
*/
put(obj: T): void {
localStorage.setItem(this.key, JSON.stringify(obj));
localStorage?.setItem(this.key, JSON.stringify(obj));
}

/**
* Retrieves a deserialized copy of the saved object, or `undefined` if it has not been set.
*/
get(): T {
const savedStr = localStorage.getItem(this.key);
return savedStr === null ? undefined : JSON.parse(savedStr);
const savedStr = localStorage?.getItem(this.key);
return savedStr == null ? undefined : JSON.parse(savedStr);
}

/**
* Deletes the saved item from local storage.
*/
clear(): void {
localStorage.removeItem(this.key);
localStorage?.removeItem(this.key);
}
}

0 comments on commit 06be1e5

Please sign in to comment.