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

react JS mapping through an object

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:

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

enter image description here

>Solution :

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}`);
  }
}
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