setState returning empty array


Component: searchPantry.jsx
Event handler: handleGroceryType

Expected: This event takes in a grocery type (produce, grains, dairy etc) and returns a list of groceries that fall into that category. I will then use that list to setState for a variable called selectGroceries. And that updated state will be used to display a series of check-boxes with those groceries as values.

Actual: Event is returning empty selectGroceries state. Using console.log, I see that the constant (which I use in setState) has the correct value(s) so not sure why end result is empty array.


  1. User clicks on the dropdown titled, “Select Ingredients” and chooses one of the 7 categories.
  2. Once the selection is made, I want to show only those groceries that fall into that category in the list below dropdown.

In between step 1 and 2 is where my problem lies and that is what I describe above.

Thank you!

I have validated that this.state.selectGroceries contains an array of only the items of the selected category after it is selected in the dropdown menu. You are not seeing it with your console.log statement, because setState is asynchronous and the console.log fires before setState has completed its task. If you want to see exactly what the state looks like after setState completes, you need to add an optional callback function to setState as a 2nd argument and use the console.log there.

this.setState({ selectGroceries }, () => console.log(this.state.selectGroceries));
1 Like

Oh awesome! Thanks so much.