javascript - waiting forEach to finish using setState in react


Keywords:javascript 


Question: 

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

3 Answers: 

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

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.