setState on React is setting my state only on the 2nd+ iteration

Viewed 44

Problem: When I 1st click the button, the offset is not adding 10, it works good from the 2nd click and so on. The same was happening with my "page" state, which I fixed with ++page instead of page++,but with the offset I want to set it to +10 on every click, and I don't think I can fix it the same way. Any idea why this is happening and how to fix it? Thanks!

 function handleRightPage(e) {
    if (offset < props.total) {
      setOffset(offset + 10);
      setFilters({
        ...filters,
        page: ++page,
      });

      if (continent && continent !== "" && displays.cont) {
        e.preventDefault();
        return props.filteredCountries(continent, orderBy, order, page, offset);
      }
      if (activity && activity !== "" && displays.act) {
        e.preventDefault();
        return props.filteredActivities(activity, orderBy, order, page, offset);
      }
    }
  }

I hope this snippet is enough, if not let me know. Thanks so much for any help/feedback!

1 Answers

When you do

setState(offset + 10)

offset will be 10 more on the next render. But you then do:

return props.filteredCountries(continent, orderBy, order, page, offset);

which is still using the initial value of offset. You really should just do:

function handleRightPage(e) {
  if (offset < props.total) {
    offset += 10;
    page++;
    setOffset(offset);
    setFilters({
      ...filters,
      page,
    });

    if (continent && continent !== "" && displays.cont) {
      e.preventDefault();
      return props.filteredCountries(continent, orderBy, order, page, offset);
    }
    if (activity && activity !== "" && displays.act) {
      e.preventDefault();
      return props.filteredActivities(activity, orderBy, order, page, offset);
    }
  }
}

and then it will all just work - you set your local version of offset to the new value and call setOffset with the new value

Related