Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to destructure an Object from Array with useState in React

I need to destructure the filter Object from Array with useState in React, but I can’t get it.

  const [filter, setFilter] = useState([]);
  const { column, comparison, value } = filter;
  console.log(column); // undefined

I tried braces, brackets, and still getting undefined.
Does anyone knows how to get that values?

The filter object:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  filter: [
    {
      column: 'population',
      comparison: 'greater than',
      value: '100000',
    }
  ]

Console log:

enter image description here

>Solution :

Based on your latest screenshot of the entire component, the problem is that you are destructuring the filterByNumericValues array before it is hydrated with the data. Then your console.log has the correct data because it is in the useEffect hook AFTER the state has been updated with the data.

Since it looks like you are only using the column, comparison, and value variables in the checkFilterByNumeric function, I would destructure the state in that scope.

function checkFilterByNumeric(planet) {
  const { column, comparison, value } = filterByNumericValues[0];

  if (comparison === "maior que") {
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading