Jak111
Jak111

Reputation: 119

React update component after setState

I have a function to get the width of the container. This function gets called every time, when the window changes the size. In this function I set the state "containerWidth" to the current width of the container. I need the width, for the function getNumberOfItems which calculates how many items fit into the container. But when I change the window size and set the state "containerWidth" the function "getNumberofItems" doesn't update. How can I achieve that the function "getNumberOfItems" gets called every time when the window size changes (with the new state containerWidth)?

Thanks for your help

  getContainerWidth() {
    let width = document.getElementsByClassName('container')[0].offsetWidth + 'px';
    this.setState({
      containerWidth: width,
    });
  }

getNumberOfItems(){
  let width = this.state.containerWidth;
  let postWidth = this.state.postWidth;
  ...
  ...
  ...
  return numberOfItems;
}

componentDidMount() {
    window.addEventListener("resize", this.getContainerWidth.bind(this));
  }

  componentWillMount() {
    this.getContainerWidth.bind(this);
    this.getNumberOfItems();
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.getNumberOfItems.bind(this));
  }

Upvotes: 2

Views: 2264

Answers (2)

craigjames
craigjames

Reputation: 81

setState method takes a callback method as the second argument. So you could do:

getContainerWidth() {
let width = document.getElementsByClassName('container')[0].offsetWidth + 'px';
this.setState({
  containerWidth: width,
},this.getNumberOfItems);

}

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281646

Since componentWillMount is only called one before the components mounts, the getNumberOfItems function is not being called on containerWidth change, what you can do is call it from the componentDidUpdate function like

componentDidUpdate(prevProps, prevState) {
    if(this.state.containerWidth !== prevState.containerWidth) { 
        this.getNumberOfItems();
    }
}
getNumberOfItems(){
  let width = this.state.containerWidth;
  let postWidth = this.state.postWidth;
  ...
  ...
  ...
  return numberOfItems;
}

Upvotes: 2

Related Questions