Sharon Chai
Sharon Chai

Reputation: 517

waiting forEach to finish using setState in react

How do I wait for setState in a foreach to finish then show the render?

class App extends Component {
  componentDidMount() {
    someArrOfObject.forEach(o => {
      this.setState({
        [`list_for_${o.id}`]: o.val
      })
    })
  }

  render() {

    const { selected_id } = this.state
    const selected_list = this.state[`list_for_${selected_id}`]

    return selected_list.map(o => <div>{o.val}</div>)
  }
}

Upvotes: 1

Views: 2639

Answers (3)

Stan Mazhara
Stan Mazhara

Reputation: 826

You need to build your state first and then call setState once.

Something like this

componentDidMount() {
  state = someArrOfObjects.reduce((a, o) => {
    return Object.assign(a, {[`list_for_${o.id}`]: o.val})
  }, {})

  this.setState(state)
}

Upvotes: 1

KapilDev Neupane
KapilDev Neupane

Reputation: 584

If you mean that you want React to render after all the changes to this.state has been made, then you don't have to do anything. React waits for several changes to be made to this.state before actually actually changing the state. Then only it the render function is called.

If what you mean is that you want to load every thing before render() is ever called, then what you want is componentWillMount() not componentDidMount().

Hope that helps.

Upvotes: 0

Amit Dhaka
Amit Dhaka

Reputation: 178

class App extends Component {
  componentDidMount() {
    let newState = {};
    someArrOfObject.forEach(o => {
      {
        newState[`list_for_${o.id}`] = o.val;
      })
    })
    this.setState(newState);
  } 
  render() {

    const { selected_id } = this.state
    const selected_list = this.state[`list_for_${selected_id}`]

    return selected_list.map(o => <div>{o.val}</div>)
  }
}

Upvotes: 4

Related Questions