Search code examples
react-nativeasync-awaitscreen

wait for the asynchronous method to finish and pass the result to another screen


hi everyone i'm just learning react native and i have a question. How do I wait for an asynchronous method to finish and then pass the result to another screen? My code is:

export default class AAA extends Component {
constructor(props){
    super(props); 
    this.state={
      comments: [],
      datetime: []      
    }
}
//getPost is a network call which gets and store the result in the state of the class  
  async getPost(){
    const utils=new Utils();
    const responseJson = await utils.getPost("ok","yes")
    const comment = (responseJson?.posts ?? []).map((data) => data.comment)
    this.setState({comments:comment})
  console.log("now i change state with new value")
    }
  componentDidMount(){
this.getPost()
  } 
  render(){ 
  return(
    <NextScreen
    comment={this.state.comments} 
    />
  )
}
}

I want the getPost () method to finish and then go to the other screen, passing the result of the getPost () method. I tried to use the componentWillMount method as well but it is deprecated. How can I do?


Solution

  • You can use conditional rendering in this case as follows:

    render() {
    
      if (this.state.comments.length === 0) {
        return null;
      } 
    
      return (
        <NextScreen
        comment={this.state.comments} 
        />
      )
    }
    

    The initial state comments contains an empty array, thus it is never undefined. However, its length is equal to zero until the async call returns with its result.