Skip to content

Instantly share code, notes, and snippets.

@509dave16
Created December 5, 2017 05:45
Show Gist options
  • Save 509dave16/7c77b4289cf1882e6a768accc6e43160 to your computer and use it in GitHub Desktop.
Save 509dave16/7c77b4289cf1882e6a768accc6e43160 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableHighlight,
Button
} from 'react-native';
const Realm = require('realm');
export default class RealmChangeDetection extends Component {
constructor(props) {
super(props);
this.state = {
realm: null,
dogs: [],
changes: { deletions: [], insertions: [], modifications: [] }
};
}
componentWillMount() {
this.realmDefaultOpen();
}
realmDefaultOpen = (user) => {
Realm.open({
path: 'realm-change-detection',
schema: [{name: 'Dog', properties: {name: 'string'}}]
})
.catch((error) => {
console.log(error);
})
.then(realm => {
const dogs = realm.objects('Dog');
dogs.addListener(this.dogsListenerCallback);
this.setState({ dogs, realm });
});
}
dogsListenerCallback = (collection, changes) => {
console.log('collection', collection);
console.log('collectionLength', collection.length);
console.log('changes', changes);
if (changes) {
this.setState({ changes });
}
}
render() {
console.log(this.state);
const info = this.state.dogs
? 'Number of dogs in this realm: ' + this.state.dogs.length
: 'Loading...';
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{info}
</Text>
<View>
<Text style={styles.welcome}>
Deletions: {this.state.changes.deletions.join(',')}
</Text>
<Text style={styles.welcome}>
Insertions: {this.state.changes.insertions.join(',')}
</Text>
<Text style={styles.welcome}>
Modifications: {this.state.changes.modifications.join(',')}
</Text>
</View>
<Button onPress={this.addDog} title="Add Rex"></Button>
<Button onPress={this.removeFirstDog} title="Remove First"></Button>
</View>
);
}
addDog = () => {
try {
this.state.realm.write(() => {
this.state.realm.create('Dog', { name: 'Rex' });
});
} catch (e) {
console.log("Error on creation of Dog");
console.log(e);
}
}
removeFirstDog = () => {
try {
this.state.realm.write(() => {
this.state.realm.delete(this.state.dogs[0]);
});
} catch (e) {
console.log("Error on removal of first Dog.");
console.log(e);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment