-
-
Save mjstelly/bc0a10d4be6d8026e4bfa9623a0be4d9 to your computer and use it in GitHub Desktop.
Problem: realm.isClosed is undefined
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useState} from 'react'; | |
import {View, Text, StyleSheet} from 'react-native'; | |
import Realm from 'realm'; | |
const App = () => { | |
const [state, setState] = useState(''); | |
// replace componentDidMount() | |
// The problem: Using a second useEffect to replace componentWillUnmount was incorrect. | |
// The solution was to remove the executed code from that useEffect and simply call it directly | |
// from the return() function. Kudos to @foyarash and @pratyaksh on Reactiflux #react-native channel | |
useEffect(() => { | |
Realm.open({ | |
schema: [{name: 'Dog', properties: {name: 'string'}}], | |
}).then(realm => { | |
realm.write(() => { | |
realm.create('Dog', {name: 'Rex'}); | |
}); | |
setState({realm}); | |
}); | |
//replaces componentWillUnmount | |
return () => { | |
if (Realm !== null && !Realm.isClosed) { | |
Realm.close(); | |
} | |
}; | |
}, []); | |
const info = state.realm | |
? 'Number of dogs in this Realm: ' + state.realm.objects('Dog').length | |
: 'Loading...'; | |
return ( | |
<View style={styles.container}> | |
<Text style={styles.welcome}>{info}</Text> | |
</View> | |
); | |
}; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
welcome: { | |
backgroundColor: 'cyan', | |
}, | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment