Search code examples
javascriptreactjsreact-lifecycle

React: setState is not rendering the page again


I am struggling with React and the lifecycles. I try to implement a very simple Next button which shows the next page with a next set of items. When I change manually the state offset to 3, the page is rendered correctly with the next items. But when I use setState by using a button, the new items are not loaded. I assume it has something to do with lifecycles, but I don't get it yet.

class EventsListContainer extends React.Component {
  state = {
    limit: 3,
    offset: 0
  };

  componentDidMount() {
    const { loadEvents } = this.props;
    const { limit, offset } = this.state;
    loadEvents(limit, offset);
  }

  onClickHandler = () => {
    this.setState({ limit: 3, offset: 3 });
    const { limit, offset } = this.state;
    loadEvents(limit, offset);
  };

  render() {
    const { events, isLoggedIn } = this.props;

    return (
      <div>
        <EventsList events={events} isLoggedIn={isLoggedIn} />
        <Button onClick={() => this.onClickHandler()}>Next</Button>
      </div>
    );
  }
}


Solution

  • The call on setState is asynchronous. You can fix it by adding a callback e.g.

    this.setState({ limit: 3, offset: 3 }, () => loadEvents(this.state.limit, this.state.offset));