-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemoList.js
More file actions
88 lines (76 loc) · 2.61 KB
/
DemoList.js
File metadata and controls
88 lines (76 loc) · 2.61 KB
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
import React, {Component} from 'react';
import {View, Text, FlatList, Button} from 'react-native';
import {openRealm} from './realm';
class DemoList extends Component {
constructor(props) {
super(props);
// This is the local state. a React component "reacts" (ah ah, get it?)
// when the state changes. We will use it to tell the component to re-render
// when the data changes.
this.state = {
// This is the actual list of cars used.
cars: []
};
this.onAddCarClick = this.onAddCarClick.bind(this);
this.onRemoveAllClick = this.onRemoveAllClick.bind(this);
this.updateLocalCarState = this.updateLocalCarState.bind(this);
}
// This is run only ONCE automatically when the component is mounted.
// Whe need the list of cars when the component starts, right?
componentDidMount() {
this.updateLocalCarState();
}
// Function triggered when the "Add car" button is pressed.
onAddCarClick() {
openRealm().then(realmInstance => {
realmInstance.write(() => {
// Create a new car.
const myCar = realmInstance.create('Car', {
make: 'Honda',
model: 'Civic',
miles: 1000,
});
});
// Now that the Realm DB is updated, ask the component to query again.
this.updateLocalCarState();
});
}
// Function triggered when the "Remove all" button is pressed.
onRemoveAllClick() {
openRealm().then(realmInstance => {
realmInstance.write(() => {
// Get a reference to the Car table and delete it.
const cars = realmInstance.objects('Car');
realmInstance.delete(cars);
});
// Now that the Realm DB is updated, ask the component to query again.
this.updateLocalCarState();
});
}
// Query the Realm database and update the local state.
updateLocalCarState() {
openRealm().then(realmInstance => {
// Get a reference to the Car table.
const cars = realmInstance.objects('Car');
// Update the local state with the new car list.
this.setState({
cars: cars,
});
});
}
// This function is run EVERY TIME the local state is updated.
render() {
return (
<View style={{ width: '100%' }}>
<FlatList
data={this.state.cars}
renderItem={(car) => <Text key={car.index}>{`${car.item.make} - ${car.item.model}`}</Text>}
ListEmptyComponent={() => <Text>No cars available :(</Text>}
/>
<Button title='Add a car' onPress={this.onAddCarClick} />
<Button title='Remove all cars' onPress={this.onRemoveAllClick} />
</View>
);
}
}
export default DemoList;