Realm js run query async












0














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>
);
}
}









share|improve this question



























    0














    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>
    );
    }
    }









    share|improve this question

























      0












      0








      0







      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>
      );
      }
      }









      share|improve this question













      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>
      );
      }
      }






      reactjs react-native realm






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 25 at 15:17









      r4id4

      2,28662950




      2,28662950
























          3 Answers
          3






          active

          oldest

          votes


















          0














          Have you tried fetching data on componentDidMount instead of willMount?



          WillMount requires your functions to complete before mounting begins.



          You can then add a loading UI state (spinner, sample text item etc).



          Then perhaps make your state.value a default which then you update when your query is complete.






          share|improve this answer





















          • Actually no, will give that a shot
            – r4id4
            Apr 25 at 15:48










          • tried with componentDidMount, but still no luck
            – r4id4
            Apr 25 at 15:58



















          0














          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.






          share|improve this answer





























            0














            I have solved it with setTimeout for awhile. For example:



            componentDidMount() {
            setTimeout(this.fetchData.bind(this), 0);
            }

            fetchData(){
            let events = this.realm.objects("Event");
            this.setState({
            value: events,
            });
            }





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50025884%2frealm-js-run-query-async%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Have you tried fetching data on componentDidMount instead of willMount?



              WillMount requires your functions to complete before mounting begins.



              You can then add a loading UI state (spinner, sample text item etc).



              Then perhaps make your state.value a default which then you update when your query is complete.






              share|improve this answer





















              • Actually no, will give that a shot
                – r4id4
                Apr 25 at 15:48










              • tried with componentDidMount, but still no luck
                – r4id4
                Apr 25 at 15:58
















              0














              Have you tried fetching data on componentDidMount instead of willMount?



              WillMount requires your functions to complete before mounting begins.



              You can then add a loading UI state (spinner, sample text item etc).



              Then perhaps make your state.value a default which then you update when your query is complete.






              share|improve this answer





















              • Actually no, will give that a shot
                – r4id4
                Apr 25 at 15:48










              • tried with componentDidMount, but still no luck
                – r4id4
                Apr 25 at 15:58














              0












              0








              0






              Have you tried fetching data on componentDidMount instead of willMount?



              WillMount requires your functions to complete before mounting begins.



              You can then add a loading UI state (spinner, sample text item etc).



              Then perhaps make your state.value a default which then you update when your query is complete.






              share|improve this answer












              Have you tried fetching data on componentDidMount instead of willMount?



              WillMount requires your functions to complete before mounting begins.



              You can then add a loading UI state (spinner, sample text item etc).



              Then perhaps make your state.value a default which then you update when your query is complete.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 25 at 15:47









              AMB

              9618




              9618












              • Actually no, will give that a shot
                – r4id4
                Apr 25 at 15:48










              • tried with componentDidMount, but still no luck
                – r4id4
                Apr 25 at 15:58


















              • Actually no, will give that a shot
                – r4id4
                Apr 25 at 15:48










              • tried with componentDidMount, but still no luck
                – r4id4
                Apr 25 at 15:58
















              Actually no, will give that a shot
              – r4id4
              Apr 25 at 15:48




              Actually no, will give that a shot
              – r4id4
              Apr 25 at 15:48












              tried with componentDidMount, but still no luck
              – r4id4
              Apr 25 at 15:58




              tried with componentDidMount, but still no luck
              – r4id4
              Apr 25 at 15:58













              0














              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.






              share|improve this answer


























                0














                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.






                share|improve this answer
























                  0












                  0








                  0






                  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.






                  share|improve this answer












                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 14 at 0:06









                  Alexandre GUIDET

                  579621




                  579621























                      0














                      I have solved it with setTimeout for awhile. For example:



                      componentDidMount() {
                      setTimeout(this.fetchData.bind(this), 0);
                      }

                      fetchData(){
                      let events = this.realm.objects("Event");
                      this.setState({
                      value: events,
                      });
                      }





                      share|improve this answer




























                        0














                        I have solved it with setTimeout for awhile. For example:



                        componentDidMount() {
                        setTimeout(this.fetchData.bind(this), 0);
                        }

                        fetchData(){
                        let events = this.realm.objects("Event");
                        this.setState({
                        value: events,
                        });
                        }





                        share|improve this answer


























                          0












                          0








                          0






                          I have solved it with setTimeout for awhile. For example:



                          componentDidMount() {
                          setTimeout(this.fetchData.bind(this), 0);
                          }

                          fetchData(){
                          let events = this.realm.objects("Event");
                          this.setState({
                          value: events,
                          });
                          }





                          share|improve this answer














                          I have solved it with setTimeout for awhile. For example:



                          componentDidMount() {
                          setTimeout(this.fetchData.bind(this), 0);
                          }

                          fetchData(){
                          let events = this.realm.objects("Event");
                          this.setState({
                          value: events,
                          });
                          }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 20 at 20:26

























                          answered Nov 20 at 20:09









                          genichm

                          421715




                          421715






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50025884%2frealm-js-run-query-async%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Wiesbaden

                              Marschland

                              Dieringhausen