Reputation: 33683
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?
Upvotes: 3
Views: 3613
Reputation: 3126
to access realm you need to call Realm.Open().then() ...
alter your code to be like this
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { realm: null }; // initial the state with null
}
initDB()
{
Realm.open({ // open connection
schema: [CompatibilityProduct]
}).then(realm => { // here is realm
console.log('realm1', realm);
this.setState({ realm }); // set it to state
});
};
loadResults()
{
const {realm } = this.state; // access it from state
console.log('realm2', realm);
// Write
realm.write(() => { // write to it
realm.create('CompatibilityProduct', {
compatibilityId: 18,
productId: 17,
});
});
this.setState({ realm }); // set it to state to see updates
};
render() {
// read data from it
const info = this.state.realm ? 'Number of CompatibilityProduct in this Realm: ' + this.state.realm.objects('CompatibilityProduct').length : 'Loading...';
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text onPress={this.initDB.bind(this)}> // bind to access this
Init DB
</Text>
<Text onPress={this.loadResults.bind(this)}> // bind to access this
Load Results {info}
</Text>
</View>
);
}
}
const CompatibilityProduct = { // schema is object not class
name: 'CompatibilityProduct',
properties: {
compatibilityId: {type: 'int'},
productId: {type: 'int'},
},
};
Upvotes: 3