Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/event-processor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [Unreleased]
Changes that have landed but are not yet released.

### Fixed
- Warn instead of error if window.localStorage is undefined or not functioning properly.

## [0.9.5] - February 2, 2022

### Changed
Expand Down
42 changes: 34 additions & 8 deletions packages/event-processor/src/pendingEventsStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,28 @@ import { getLogger } from '@optimizely/js-sdk-logging';

const logger = getLogger('EventProcessor')

function isLocalStorageAvailable() {
if (typeof window.localStorage == 'undefined') {
logger.warn('Local storage is undefined.');
return false;
}

try {
window.localStorage.setItem('foo', 'bar');

if (window.localStorage.getItem('foo') === 'bar') {
window.localStorage.removeItem('foo');
return true;
}

logger.warn('Local storage is not functioning as expected.');
} catch (e) {
logger.warn('Local storage is not available.');
}

return false;
}

export interface PendingEventsStore<K> {
get(key: string): K | null

Expand Down Expand Up @@ -71,9 +93,10 @@ export class LocalStorageStore<K extends StoreEntry> implements PendingEventsSto
}

replace(map: { [key: string]: K }): void {
if (!isLocalStorageAvailable()) return;
try {
// This is a temporary fix to support React Native which does not have localStorage.
window.localStorage && localStorage.setItem(this.LS_KEY, JSON.stringify(map))
localStorage.setItem(this.LS_KEY, JSON.stringify(map))
this.clean()
} catch (e) {
logger.error(e)
Expand Down Expand Up @@ -103,15 +126,18 @@ export class LocalStorageStore<K extends StoreEntry> implements PendingEventsSto
}

private getMap(): { [key: string]: K } {
try {
// This is a temporary fix to support React Native which does not have localStorage.
const data = window.localStorage && localStorage.getItem(this.LS_KEY);
if (data) {
return (JSON.parse(data) as { [key: string]: K }) || {}
if (isLocalStorageAvailable()) {
try {
// This is a temporary fix to support React Native which does not have localStorage.
const data = localStorage.getItem(this.LS_KEY);
if (data) {
return (JSON.parse(data) as { [key: string]: K }) || {}
}
} catch (e) {
logger.error(e)
}
} catch (e) {
logger.error(e)
}

return {}
}
}