Skip to content
This repository was archived by the owner on Mar 13, 2023. It is now read-only.

Commit 539ef04

Browse files
committed
refactor: make async storage a peer dependency
`@segment/analytics-react-native` has an option to create custom persistor that matches `Persistor` type from `@segment/sovran-react-native`. If it's possible, then let's mark `@react-native-async-storage/async-storage` as optional peer dependency to not force users to download it when custom persistor is used. - `@react-native-async-storage/async-storage` is marked as optional peer dependency - `@react-native-async-storage/async-storage` is optionally required (instead of being imported) in `src/persistor/async-storage-persistor.ts`
1 parent b9bf577 commit 539ef04

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,16 @@
157157
}
158158
},
159159
"peerDependencies": {
160+
"@react-native-async-storage/async-storage": "*",
160161
"react": "*",
161162
"react-native": "*"
162163
},
164+
"peerDependenciesMeta": {
165+
"@react-native-async-storage/async-storage": {
166+
"optional": true
167+
}
168+
},
163169
"dependencies": {
164-
"@react-native-async-storage/async-storage": "^1.15.15",
165170
"ansi-regex": "5.0.1",
166171
"deepmerge": "^4.2.2",
167172
"shell-quote": "1.7.3"

src/persistor/async-storage-persistor.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
import AsyncStorage from '@react-native-async-storage/async-storage';
21
import type { Persistor } from './persistor';
32

3+
let AsyncStorage: {
4+
getItem: (key: string) => Promise<string | null>;
5+
setItem: (key: string, value: string) => Promise<void>;
6+
} | null;
7+
8+
try {
9+
AsyncStorage = require('@react-native-async-storage/async-storage');
10+
} catch (error) {
11+
AsyncStorage = null;
12+
}
13+
414
/**
515
* Persistor implementation using AsyncStorage
616
*/
717
export const AsyncStoragePersistor: Persistor = {
818
get: async <T>(key: string): Promise<T | undefined> => {
919
try {
10-
const persistedStateJSON = await AsyncStorage.getItem(key);
20+
const persistedStateJSON = await AsyncStorage?.getItem?.(key);
1121
if (persistedStateJSON !== null && persistedStateJSON !== undefined) {
1222
return JSON.parse(persistedStateJSON);
1323
}
@@ -20,7 +30,7 @@ export const AsyncStoragePersistor: Persistor = {
2030

2131
set: async <T>(key: string, state: T): Promise<void> => {
2232
try {
23-
await AsyncStorage.setItem(key, JSON.stringify(state));
33+
await AsyncStorage?.setItem?.(key, JSON.stringify(state));
2434
} catch (e) {
2535
console.error(e);
2636
}

0 commit comments

Comments
 (0)