Skip to content

Commit

Permalink
Merge pull request #235 from mixpanel/zihe-fix-init-storage
Browse files Browse the repository at this point in the history
Avoid crash if AsyncStorage is null
  • Loading branch information
zihejia authored Apr 16, 2024
2 parents a68a028 + 53b39c2 commit f5cc5a0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class Mixpanel {
superProperties = {},
serverURL = "https://api.mixpanel.com"
) {
await MixpanelReactNative.initialize(
await this.mixpanelImpl.initialize(
this.token,
this.trackAutomaticEvents,
optOutTrackingDefault,
Expand Down
28 changes: 27 additions & 1 deletion javascript/mixpanel-storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@ import {MixpanelLogger} from "mixpanel-react-native/javascript/mixpanel-logger";
export class AsyncStorageAdapter {
constructor(storage) {
if (!storage) {
this.storage = require("@react-native-async-storage/async-storage");
try {
this.storage = require("@react-native-async-storage/async-storage");
} catch {
console.error(
"[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null. Please run 'npm install @react-native-async-storage/async-storage' or follow the Mixpanel guide to set up your own Storage class."
);
console.error("[Mixpanel] Falling back to in-memory storage");
this.storage = new InMemoryStorage();
}
} else {
this.storage = storage;
}
Expand Down Expand Up @@ -34,3 +42,21 @@ export class AsyncStorageAdapter {
}
}
}

class InMemoryStorage {
constructor() {
this.store = {};
}

async getItem(key) {
return this.store.hasOwnProperty(key) ? this.store[key] : null;
}

async setItem(key, value) {
this.store[key] = value;
}

async removeItem(key) {
delete this.store[key];
}
}

0 comments on commit f5cc5a0

Please sign in to comment.