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

Time:08-28

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?

CodePudding user response:

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.

CodePudding user response:

You can use react-router params if you are fetching data in the splash screen, you want to pass it to the next page.

in then() or after await expression

you can learn about this in React router, pass data when navigating programmatically?

  • Related