Search code examples
javascriptreactjsreact-nativeasyncstorage

React Native - set order for two functions


I'm new at React Native so I apologize in advance.
I have a function called setAllComments() which called from componentDidMount.
This function does AsyncStorage.setItem() and I want this function to be finished before the call for the other function - getComments(),
(That does AsyncStorage.getItem()).

The problem is that the getComments() function is executed before setAllComments() function is finished.
I tried to solve it with callback function but that stuck my application.

Anyone knows how to set order for these two function?

 async componentDidMount() {

        this.setAllComments();

      }

   
  setAllComments = () => {
    console.log("setAllComments function!");
    fetch(URL + "/CommentsList2", {
      body: null,
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json; charset=UTF-8"
      }
    })
      .then(res => {
        return res.json();
      })
      .then(commentsResult => {
        console.log("function setAllComments - before comments parse");
        AsyncStorage.setItem("@Project:comments", commentsResult.d);
        console.log("finished setItem");
      })
      .catch(err => {
        console.error(err);
      })
      .then(this.getComments());
  };

  async getComments() {
    console.log("entered getCommens");
    await AsyncStorage.getItem("@Project:comments").then(value => {
      let commentsList = JSON.parse(value);
      this.setState({ comments: commentsList });
      console.log(this.state.comments, "getComments - Player with comments");
    });
  }


Solution

  • You have multiple issues w/ your approach.

    First. AsyncStorage is well async

    AsyncStorage.setItem("@Project:comments", commentsResult.d);
    console.log("finished setItem"); // not true
    

    You need to return a promise to keep promise chain

      .then(commentsResult => {
        console.log("function setAllComments - before comments parse");
        return AsyncStorage.setItem("@Project:comments", commentsResult.d);
      }) 
      .then(() => console.log("finished setItem");) // now it is more likely :)
    

    Then .then(this.getComments()); you are immediatelly calling the function should be

    .then(() => this.getComments());
    

    And finally setState is also async (but atm it doesn't return a promise). So you'd need to pass a callback.

    this.setState(
      { comments: commentsList },
      () => console.log(this.state.comments, "getComments - Player with comments")
    );
    

    Also you are mixing async/await w/ a bunch of then/catch stick to one approach through out your code (at least within a function :))