-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
86 lines (79 loc) · 2.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-community/async-storage';
export function useStatePersist(dbName, fieldKey, fieldValue) {
let isGetStoreSubscribed = true;
function getStore() {
AsyncStorage.getItem(dbName)
.then(item => {
if (!isGetStoreSubscribed) {
return;
}
if (item !== null) {
const parsedItem = JSON.parse(item);
setValue(parsedItem);
} else {
const initObjectToSave = { [fieldKey]: fieldValue };
setStore(dbName, fieldKey, fieldValue);
setValue(initObjectToSave);
}
})
.catch(error => console.log('get Item failed with error: ', error));
}
let isSetStoreSubscribed = true;
function setStore(db, key, value) {
AsyncStorage.getItem(db)
.then(item => {
const objectCreated = typeof key === 'object' ? key : { [key]: value };
let objToSave = objectCreated;
if (item) {
const parsedItem = JSON.parse(item);
objToSave = { ...parsedItem, ...objectCreated };
}
try {
AsyncStorage.setItem(db, JSON.stringify(objToSave));
if (isSetStoreSubscribed) {
setValue(objToSave);
}
} catch (error) {
console.log('set Item failed with error: ', error);
}
})
.catch(error => console.log('get Item failed with error: ', error));
}
const [getValue, setValue] = useState(() => {
const initValue = { [fieldKey]: fieldValue };
return initValue;
});
useEffect(() => {
getStore();
return () => {
isGetStoreSubscribed = false;
isSetStoreSubscribed = false;
};
});
return [getValue, setStore];
}
export function removeStatePersist(dbName, fieldKey) {
AsyncStorage.getItem(dbName)
.then(item => {
if (item) {
const parsedItem = JSON.parse(item);
delete parsedItem[fieldKey];
try {
AsyncStorage.setItem(dbName, JSON.stringify(parsedItem));
} catch (error) {
console.log('set Item failed with error: ', error);
}
}
})
.catch(error => console.log('get Item failed with error: ', error));
}
export function debugStatePersist(dbName) {
AsyncStorage.getItem(dbName)
.then(item => {
if (item) {
console.log('Debug All State Persist: ', JSON.parse(item));
}
})
.catch(error => console.log('get Item failed with error: ', error));
}