Skip to content
Advertisement

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:

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

Console log:

enter image description here

Advertisement

Answer

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") {
  ...
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement