if I setState of returned data in side (Promise.all) the function, It causes an infinite loop

Once the promise.all is resolved, I want to setState of returned data to results, but currently not able to do so. checkData has the correct data that I need. how can I avoid infinite loop and just setState of returned data.

note: results will then be passed on to the child components

  getEndResult = async () => {
    const userId = await this.getUserId(userId);
    const userData = await this.getUserData(userId);

    const checkData = await Promise.all(userData.checks.map(check => {
    return check.checkIds.map((checkIds) => {
        return this.getUserCredits(userId ,checkIds)
            .then(res => res.json())
            .then(data => console.log(data))

            // Can't setState here - causes infinite loop
            // .then(data => this.setState({ results: data }))
        })
    }))

    // Can't setState here - causes infinite loop
    this.setState({ checkData: data }))
    console.log(checkData);
  }

calling it here which is in child component

case getUserDetails(Constants.CREDITSTATUS): {

  getEndResults(userId);

  modalBody = (
    <UserDetailsModal
      userDetails={jd}
      setForm={this.setForm}
      updateActivity={updateActivity}
      updateUser={updateUser}
      updateUserDetails={updateUserDetails}
    />
  );
  break;
}

passing down to child component

render() {

  return (
    <div>
      <Route
        exact
        render={() => {
          return (
            <Overview
              getRecommendationResult={this.getRecommendationResult}
            />
          );
        }}
      />

2 answers

  • answered 2019-09-10 02:27 Ajay Ghosh

    If you are calling the getresult function from use-effect function, this will cause to re-render the component on each state value changes. In case of use-effect function add dependency inside it to avoid running the function again and again.

  • answered 2019-09-10 02:46 Vu Luu

    Let's try to create an Array to store the promises like:

    let promises = []
    userData.checks.map(check => {
      check.checkIds.map((checkIds) => {
        promises.push(this.getUserCredits(userId ,checkIds)
      }
    }
    const checkData = await Promise.all(promises).then((values) => {
      console.log(values);
    });