-1
class Filters extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentWillReceiveProps(nextProps) {
    nextProps.dataAsProp.map(data => {
      if (data.productList.length == 0)
       this.setState({ count: this.state.count + 1 });
     });

}

How do I update the value of count for each data who's produclist is a null array. It only prints one. It doesn't count for all the data in dataAsProp.

Varun thadhani
  • 691
  • 1
  • 5
  • 7
  • everytime the parent rerenders the componentWillReceiveProps of child is called, so This what mayank suggested may not work properly, could you explain you usecase a little – Shubham Khatri Jul 19 '17 at 06:58

1 Answers1

1

Reason is setState is asynchronous so we can't predict the updated value in loop iteration.

Changes:

1.Instead of doing setState multiple times, first calculate the value and then at the end update the state count value once.

2.Use forEach instead of map.

Write it like this:

componentWillReceiveProps(nextProps) {

    /*put the check here, perform this operation only when there a change between nextProps and prev props values*/

     let count = 0;
     nextProps.dataAsProp.forEach(data => {
        if (data.productList.length == 0)
            count++;
     });
     this.setState({ count });
}

Check this answer for difference between forEach and map.

check this answer for more details about asynchronous behaviour of setState :

Why calling setState method doesn't mutate the state immediately?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142