0

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 Answer 1

2

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}`);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.