Search code examples
javascriptreactjsreact-nativerendersetstate

Multiple setState inside componentDidMount


Is it possible to have multiple setState inside componentDidMount()?

I have this structure of code and each of console logs is actually giving me the correct values.

  constructor(props) {
    super(props);

    this.state = {
      index : 0,
      index2 : 0
    };
  }

  componentDidMount() {
    fetch(url)
      .then(response => response.json())
      .then(data => {

        // 1st setState
        var index = 0;
        for (var i = 0; i < data.length; i++) {
          //somecode
        }
        this.setState({ index : index});
        console.log("this.state.index" , this.state.index); // value: 1

        // 2nd setState
        var index = 0;
        for (var i = 0; i < data.length; i++) {
          //somecode
        }
        this.setState({ index2 : index});
        console.log("this.state.index2" , this.state.index2); // value: 2
      })
  }

  render() {
    value1={this.state.index}
    value2={this.state.index2}
  }

However, when I call it inside render(), it seems thats is still using the initial values set in the constructor.

How to deal with this approach? Thanks!


Solution

  • Yes, there is no issue in using multiple setState but it is not recomended because it will trigger render everytime. Inspite you can use one setState at the end of componentDidMount.

    for example:

    componentDidMount() {
    fetch(url)
      .then(response => response.json())
      .then(data => {
    
        // 1st setState
        var index = 0;
        for (var i = 0; i < data.length; i++) {
          //somecode
        }
        //this.setState({ index : index});
        console.log("this.state.index" , this.state.index);
    
        // 2nd setState
        var index = 0;
        for (var i = 0; i < data.length; i++) {
          //somecode
        }
        //this.setState({ index2 : index});
        this.setState({
          index,
          index2: index,
          key1: value1,
        })
        console.log("this.state.index2" , this.state.index2);
      })
    }