-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
103 lines (92 loc) · 2.14 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import React, {useState, useEffect} from 'react';
import Realm from 'realm';
import {
View,
TextInput,
StyleSheet,
TouchableOpacity,
Text,
FlatList,
} from 'react-native';
const TodoSchema = {
name: 'Todo',
properties: {
name: 'string',
},
};
const App = () => {
const [text, setText] = useState('');
const [realm, setRealm] = useState(null);
const [todos, setTodos] = useState([]);
useEffect(() => {
Realm.open({schema: [TodoSchema]}).then((realm) => setRealm(realm));
return () => {
if (realm !== null && !realm.isClosed) realm.close();
};
}, []);
useEffect(() => {
if (realm !== null) {
realm.objects('Todo').addListener(todoListener);
}
return () => {
if (realm !== null) realm.removeAllListeners();
};
}, [realm]);
const todoListener = (collection, changes) => {
//collection.sorted('name');
console.log(collection.filtered('name == $0', 'test'));
setTodos(collection);
};
const addTodo = () => {
if (realm != null) {
realm.write(() => {
realm.create('Todo', {
name: text,
});
});
setText('');
}
};
return (
<View style={{flex: 1}}>
<View
style={{
height: 60,
marginHorizontal: 16,
marginVertical: 16,
flexDirection: 'row',
}}>
<TextInput
placeholder="Todo"
value={text}
onChangeText={setText}
style={styles.textInput}
/>
<TouchableOpacity
onPress={() => addTodo()}
style={{justifyContent: 'center', alingSelf: 'center', margin: 16}}>
<Text style={{fontSize: 40}}>+</Text>
</TouchableOpacity>
</View>
<FlatList
data={todos}
keyExtractor={(item) => `${(Math.random() * 1000).toString()}`}
renderItem={({item}) => (
<View>
<Text>{item.name}</Text>
</View>
)}
/>
</View>
);
};
const styles = StyleSheet.create({
textInput: {
paddingVertical: 16,
paddingHorizontal: 16,
borderWidth: 1,
borderColor: 'black',
flex: 1,
},
});
export default App;