-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
85 lines (78 loc) · 1.91 KB
/
App.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
import React, {
useCallback,
useEffect,
useState
} from "react";
import {
Text,
TextInput,
SafeAreaView
} from "react-native";
import Realm from "realm";
const usersSchema = {
name: 'users',
properties: {
_id: 'string?',
_partitionKey: 'string?',
name: 'string?',
},
primaryKey: '_id',
};
function useRealm(props) {
const [realm, setRealm] = useState(null);
useEffect(async () => {
const app = new Realm.App({"id": "application-0-abyjh"})
await app.logIn(Realm.Credentials.function({"_id": props.userId}));
const openRealmBehaviorConfiguration = {
type: "openImmediately"
};
const realm = await Realm.open({
"schema": [usersSchema],
"sync": {
user: app.currentUser,
partitionValue: props.userId,
newRealmFileBehavior: openRealmBehaviorConfiguration,
existingRealmFileBehavior: openRealmBehaviorConfiguration
}
});
setRealm(realm);
return () => {
realm.close();
}
}, [props.userId]);
return realm;
}
export default function(props) {
const userId = "QW5SVRZ4YWORLP2YVJZVO";
const realm = useRealm({userId});
const [user, setUser] = useState(null);
const [text, setText] = useState(user?.name);
useEffect(() => {
const user = realm?.objectForPrimaryKey("users", userId);
setUser(user);
setText(user?.name);
const onUserChange = (user, changes) => {
changes.changedProperties.forEach((prop) => {
if (prop === "name") {
setText(user[prop]);
}
})
}
user?.addListener(onUserChange);
return () => {
user?.removeListener(onUserChange);
}
}, [realm]);
const onEndEditing = useCallback(() => {
realm?.write(() => {
user.name = text;
});
}, [realm, user, text]);
return <SafeAreaView>
<TextInput
value={text}
onChangeText={setText}
onEndEditing={onEndEditing}
/>
</SafeAreaView>
}