Skip to content

Instantly share code, notes, and snippets.

@mjstelly

mjstelly/App.js Secret

Last active December 14, 2022 17:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjstelly/bc0a10d4be6d8026e4bfa9623a0be4d9 to your computer and use it in GitHub Desktop.
Save mjstelly/bc0a10d4be6d8026e4bfa9623a0be4d9 to your computer and use it in GitHub Desktop.
Problem: realm.isClosed is undefined
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