I'm using Realm for the first time, and I'm simply trying to initialize a database and write a record to it. Here's my code.
import React, { Component } from 'react';
import {StackNavigator} from 'react-navigation';
import Realm from 'realm';
import {
AppRegistry,
StyleSheet,
Text,
View,
Linking
} from 'react-native';
class Home extends Component {
static navigationOptions = {
title: 'Login',
headerStyle: {
backgroundColor:'#000000'
},
headerTitleStyle: {
color:'#fff'
}
};
initDB()
{
const realm = new Realm({schema: [CompatibilityProduct]});
this.realm = realm;
console.log(realm);
};
loadResults()
{
const realm = this.realm;
console.log(realm);
// Write
realm.write(() => {
realm.create('CompatibilityProduct', {
compatibilityId: 18,
productId: 17,
});
});
};
constructor(props)
{
super(props);
}
render() {
const {navigate} = this.props.navigation;
return (
<View>
<Text onPress={this.initDB}>
Init DB
</Text>
<Text onPress={this.loadResults}>
Load Results
</Text>
</View>
);
}
}
const myscreens = StackNavigator({
Home: {screen: Home}
});
class CompatibilityProduct {}
CompatibilityProduct.schema = {
name: 'CompatibilityProduct',
properties: {
compatibilityId: {type: 'int'},
productId: {type: 'int'},
},
};
export default myscreens;
I start up the app in my AVD, I click on Init DB (console.log(realm) is empty in the initDB() function), then when I click on Load Results, the app crashes because this.realm is undefined.
What am I doing wrong?