React Native - set order for two functions

44
December 30, 2018, at 10:20 PM

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

Answer 1

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 :))

Answer 2

For being new you are doing great using asyn, but that's not the way async is supposed to work. async has an awesome feature or "word" to work with, it's called "await", exactly what you want. It awaits an async function and there is no need to use ".then()"

Your function with async should be like

 async componentDidMount() {
        await this.setAllComments();
        await this.getComments()
      }

  setAllComments = async () => {
    //console.log("setAllComments function!");
    var fetchresult = await fetch(URL + "/CommentsList2", {
      body: null,
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json; charset=UTF-8"
      }
    })
    fetchresult = await fetchresult.json()
    //console.log("function setAllComments - before comments parse");
    await AsyncStorage.setItem("@Project:comments", fetchresult.d).catch(err => {
        console.error(err);
      })
    //console.log("finished setItem")
  };
  async getComments() {
    //console.log("entered getCommens");
    let commentsList = await AsyncStorage.getItem("@Project:comments")
       commentsList = JSON.parse(Comments)
      this.setState({ comments: commentsList });
      //console.log(this.state.comments, "getComments - Player with comments");
    });
  }
READ ALSO
Having trouble passing an apostrophe or double quote through a clickable link

Having trouble passing an apostrophe or double quote through a clickable link

I have some code that receives a string (that might have an apostrophe or double quote in it)On receipt of the string, a link is created to allow the user to utilize the string in an input

47
HTML - Either browser or handlebars is removing / ignoring a <table><tr><td> tag

HTML - Either browser or handlebars is removing / ignoring a <table><tr><td> tag

I have a table class that I use to vertically centralise text in a span or divI am using Handlebars in Node to render several templates server side, I have used this method on several partials in my web project, with no problems

13
Multiprocessing function not writing to file or printing

Multiprocessing function not writing to file or printing

I'm working on a Raspberry Pi (3 B+) making a data collection device and I'm trying to spawn a process to record the data coming in and write it to a fileI have a function for the writing that works fine when I call it directly

20
centering a video and a input box using flexbox

centering a video and a input box using flexbox

I have a bit of a problem horizontally centering my video, input box and button in the center of the pageI've seen a few answers that say that I don't need flexbox and I've actually attempted to set my margin to auto(to center the content in the middle...

18