question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error: Cannot access realm that has been closed

See original GitHub issue

Hello, Realm keeps throwing this error in a simple use case: Cannot access realm that has been closed The example I am using is available at the react-native-realm repo: RealmExample.js

import Realm from 'realm';

class Item {}
Item.schema = {
  name: 'Item',
  properties: {
    name:  'string',
    date: 'date',
    id: 'string'
  },
};
export default new Realm({schema: [Item]});

app.js

//My imports
export default class App extends Component<{}> {
  render() {
    return (
      <RealmProvider realm={realm}>
        <ConnectedExample />
      </RealmProvider>
    );
  }
}

ConnectedExample.js

import React, { Component } from 'react';
import {
  Text,
  ScrollView,
  TouchableOpacity,
  View,
  StyleSheet,
} from 'react-native';
import uuid from 'uuid';
import { connectRealm } from 'react-native-realm';
import ConnectedExampleItem from './ConnectedExampleItem';

const styles = StyleSheet.create({
  screen: {
    paddingTop: 20,
    paddingHorizontal: 10,
    backgroundColor: '#2a2a2a',
    flex: 1,
  },
  add: {
    height: 44,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 10,
    backgroundColor: '#1a1a1a',
  },
  addText: {
    color: 'white',
  },
});

class ConnectedExample extends Component {

  count = 0;

  onPressAddItem = () => {
    const { realm } = this.props;
    realm.write(() => {
      realm.create('Item', {
        name: this.count.toString(),
        date: new Date(),
        id: uuid.v4(),
      });
      this.count++;
    });
  };

  render() {
    return (
      <View style={styles.screen}>
        <TouchableOpacity onPress={this.onPressAddItem} style={styles.add}>
          <Text style={styles.addText}>Add Item</Text>
        </TouchableOpacity>
        <ScrollView>
          {this.props.items.map((item) => (
            <View key={item.id}>
              <ConnectedExampleItem id={item.id} />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

export default connectRealm(ConnectedExample, {
  schemas: ['Item'],
  mapToProps(results, realm) {
    return {
      realm,
      items: results.items.sorted('date') || [],
    };
  },
});

ConnectedExampleItem.js

import React, {
  Component,
  PropTypes,
} from 'react';
import {
  StyleSheet,
  TouchableOpacity,
  Text,
} from 'react-native';
import { connectRealm } from 'react-native-realm';

const styles = StyleSheet.create({
  item: {
    height: 44,
    justifyContent: 'center',
    paddingHorizontal: 10,
    marginTop: 10,
    backgroundColor: 'cyan',
  },
});

class ConnectedExampleItem extends Component {

  onPressRemoveItem = (item) => {
    const { realm } = this.props;
    realm.write(() => {
      realm.delete(item);
    });
  };

  render() {
    return (
      <TouchableOpacity
        onPress={() => this.onPressRemoveItem(this.props.item)}
        style={styles.item}
      >
        <Text>{this.props.item.name}</Text>
      </TouchableOpacity>
    );
  }

}

export default connectRealm(ConnectedExampleItem, {
  schemas: ['Item'],
  mapToProps(results, realm, ownProps) {
    return {
      realm,
      item: results.items.find(item => item.id === ownProps.id),
    };
  },
});

Running this example in a mint project runs fine. However, when I add Realm to my own project, I run into the Cannot access realm that has been closed (I haven’t instantiated Realm anywhere else) Also, trying the example here works fine as well.

This error is mentioned nowhere in the docs or in SO. What could be causing this? How do I fix it? Thank you.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:3
  • Comments:22 (7 by maintainers)

github_iconTop GitHub Comments

10reactions
Friendly-Robotcommented, Feb 3, 2018

+1 Same issue here.

After calling realm.close() the application keeps getting this error even after a reinstall. The realmjs example doesn’t include a usage of realm.close() but it’s used once in the RealmJS docs here:

// Initialize a Realm with Car and Person models
Realm.open({schema: [CarSchema, PersonSchema]})
    .then(realm => {

        // Add persons and their cars
        realm.write(() => {
            let john = realm.create('Person', {name: 'John', cars: []});
            john.cars.push({make: 'Honda',  model: 'Accord', miles: 1500});
            john.cars.push({make: 'Toyota', model: 'Prius',  miles: 2780});

            let joan = realm.create('Person', {name: 'Joan', cars: []});
            joan.cars.push({make: 'Skoda', model: 'Octavia', miles: 1120});
            joan.cars.push({make: 'Ford',  model: 'Fiesta',  miles: 95});
            joan.cars.push({make: 'VW',    model: 'Golf',    miles: 1270});

            let jill = realm.create('Person', {name: 'Jill', cars: []});

            let jack = realm.create('Person', {name: 'Jack', cars: []});
            jack.cars.push({make: 'Porche', model: '911',    miles: 965});
        });

        // Find car owners
        let carOwners = realm.objects('Person').filtered('cars.@size > 0');
        console.log('Car owners')
        for (let p of carOwners) {
            console.log(`  ${p.name}`);
        }

        // Find who has been driver longer than average
        let average = realm.objects('Car').avg('miles');
        let longerThanAverage = realm.objects('Person').filtered('cars.@sum.miles > $0', average);
        console.log(`Longer than average (${average})`)
        for (let p of longerThanAverage) {
            console.log(`  ${p.name}: ${p.cars.sum('miles')}`);
        }

        realm.close();    <========================================== **here**
});

Is using realm.close() a strict requirement to prevent memory leakage or can I continue getting by without ever using it? Also, how on earth do I open the Realm again after a realm.close() without refactoring my code for every instance to use:

Realm.open({schema: [Schema]})
  .then(realm => { ... })

Currently I am doing export default new Realm({schema: [Schema]}) and importing as realm so I do not see a way to do a Realm.open() with my imported realm instance. Whenever I attempt to either do a realm.write() or realm.beginTransaction(), I receive the same Error: Cannot access realm that has been closed. Sorry for the long post, I’ve looked everywhere for a solution and ended up here again.

4reactions
franzejrcommented, Feb 27, 2018

@Unforgiven-wanda this is happening on the Android side? I got the same error, but only in Android.

Read more comments on GitHub >

github_iconTop Results From Across the Web

react native Android Cannot access realm that has been closed
im using Realm inside my React native app, in IOS everything work fine, but with Android I always got this error: Cannot access...
Read more >
Errors - Realm Support
Error: Cannot access realm that has been closed. This error is generally triggered by our GraphQL Service Realm's GraphQL Service works by querying...
Read more >
Realm not closing? - MongoDB
Got an issue with Realm with React Native (v0.64.1). ... Noticed I have closed the instance so why am I getting error when...
Read more >
The things I've learned using Realm | by Gabor Varadi - Medium
In this article, I try to sum up all the things I've learned from using Realm, and how it all relates with the...
Read more >
Minecraft Realms Plus: How do I Join Someone's Minecraft ...
A child account cannot access Realms unless the account has been given parental consent. These accounts can still join other private worlds and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found