react JS mapping through an object

Viewed 15

I have an API that's returning me the categories and subcategories of 6 different stores the list might change between stores i want to map thru all the keys and values without having to specify what key i want (ex data.Baby, Baby Healthcare) i tried object.enteries

function FetchedData() {
  const [data, setData] = useState();



 const getApiData = async () => {
 const response = await fetch(
   `https://api/admin_stats`      
  ).then((response) => response.json());
 setData(response);
};

useEffect(() => {
 getApiData();
// eslint-disable-next-line
}, []);

for (const [key, value] of Object.entries(data)) {
  console.log(`${key}: ${value}`);
}

However i kept getting the error ' Uncaught TypeError: Cannot convert undefined or null to object at Function.entries ()'

this is the data:

enter image description here

1 Answers

The initial default value for data is undefined:

const [data, setData] = useState();

So on the first render this will fail with that exact error:

for (const [key, value] of Object.entries(data)) {

You can set the initial value to an empty object:

const [data, setData] = useState({});

Or perhaps not perform the operation at all if data is null or undefined:

if (data) {
  for (const [key, value] of Object.entries(data)) {
    console.log(`${key}: ${value}`);
  }
}
Related