Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm js run query async

I'm using React-Native with Realm Database.
I tried to run read queries using the async/await pattern but it looks like it's always executing synchronously, freezing the UI since the query takes at least a couple of second till the rendering (due to a possible large amount of data stored).

This is the code I'm using (it's a copy and paste, but to give you an idea), am I missing something?

export default class CustomComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     value:0
   };
   this.realm = this.buildRealm();
 }

  buildRealm() {
        return new Realm({ schema: [EventSchema] });
 }

  componentWillMount() {
    this.fetchData().then(result => { this.setState(value:result);});
  }

  async fetchData() {    
    var appState = await someMethod()
    return appState;
  }

  someMethod() {
   return new Promise(resolve => {
         resolve(queryFromDB())
        });
  }

  queryFromDB() {
     // Returns a value fetched from Realm
     let events = this.realm.objects("Event");
     return events.length;
   }

  render() {
   return (
     <Text> {this.state.value} </Text> 
   );
  }
}
like image 465
r4id4 Avatar asked Dec 09 '25 18:12

r4id4


1 Answers

Realm query is synchronous, there is no way to make it async. Look like you are using realm with React Native, if this is the case, the best solution is to defer your realm query using the interaction manager

async componentDidMount() {
  // loading objects from realm is a synchronous task that block the main
  // process, in order not to freeze the ui, we trigger the load after
  // the interactions and screen loading is done
  this.getRealmDataHandle = InteractionManager.runAfterInteractions(() => this.getRealmData())
}

componentWillUnmount() {
  if (this.getRealmDataHandle !== undefined) {
    this.getRealmDataHandle.cancel()
  }
}

First your component mount and render a loading screen, then when the ui rendering thread has finished it's work, the interaction manager will trigger the realm query. This way, the user is not experiencing too much of UI freezing.

I hope someday the realmJS team will provide an async version, but I doubt this will happen soon.

like image 130
Alexandre GUIDET Avatar answered Dec 11 '25 10:12

Alexandre GUIDET



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!