Skip to content

Instantly share code, notes, and snippets.

@mjstelly
Last active May 29, 2020 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjstelly/6287bb693fd7876c65471193ee717e24 to your computer and use it in GitHub Desktop.
Save mjstelly/6287bb693fd7876c65471193ee717e24 to your computer and use it in GitHub Desktop.
Updated working RealmDB example
import React from 'react';
import {View, Text, StyleSheet, Button, Alert} from 'react-native';
import Realm from 'realm';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
welcome: {
backgroundColor: 'cyan',
},
});
const DogSchema = {name: 'Dog', properties: {name: 'string'}};
const realm = new Realm({
schema: [DogSchema],
deleteRealmIfMigrationNeeded: true,
});
const App = () => {
const [state, setState] = React.useState({});
React.useEffect(() => {
realm.write(() => {
realm.create('Dog', {name: 'Rex'});
});
setState({realm});
}, []);
function handleCloseDatabase() {
console.log(realm.objects('Dog').length);
realm.close();
Alert.alert('DB Closed.');
return;
}
console.log(realm);
const info = state.realm
? 'Number of dogs in this Realm: ' + state.realm.objects('Dog').length
: 'Loading...';
console.log(info);
return (
<View style={styles.container}>
<Text style={styles.welcome}>{info}</Text>
<Button title="Close Database" onPress={handleCloseDatabase} />
</View>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment