Home > Back-end >  React useState being set to empty array
React useState being set to empty array

Time:04-30

I'm trying to use the useState hook to select an option from a dropdown menu and affect the rest of the component. I have the exact same system working in a different component, but for some reason it's only setting the previous value of the selectedRegion variable.

This is the code

  const [regions, setRegions] = useState([])
  const [selectedRegion, setSelectedRegion] = useState([])
  const handleSetRegion = (index) => {
    console.log("Region - "   regions[index].name)
    setSelectedRegion(regions[index])
    console.log("Selected Region - "   selectedRegion.name)
  }

This is my output the first time I select from the dropdown menu.

Region - Toronto
Selected Region - undefined

And this is my output after I select a second item from the dropdown menu.

Region - Calgary
Selected Region - Toronto

The dropdown menu is passing the correct value to the handleSetRegion function, and it's getting the correct value from the regions array, but it keeps returning the previous value that was passed. Any ideas about this are much appreciated.

CodePudding user response:

it is because useState hook is asynchronous! it takes time to set it, here is a link to help you understand it better: useState hook is asynchronous!

CodePudding user response:

setRegions and setSelectedRegion actually add instructions to a queue, they do not directly modify the state variables themselves. Check out this article which explains this in more detail.

  • Related