Tuesday, October 18, 2022

Can't get array length after fetch object destructuring

Cannot read properties of undefined (reading 'length'):

const { posts = [] } = data; // destructuring array from data
console.log(posts.length);

https://bobbyhadz.com/blog/javascript-cannot-read-property-length-of-undefined

const { data: { posts } = [] } = data; // extract arr didn't work out
const arr = posts || []; // empty array fallback
console.log(arr.length); // getting error in React

In React console.log after fetch like this:

const postsData = () => (
<>
{console.log(posts.length)}
</>
);
return (postsData());

https://leocode.com/development/how-to-deal-with-async-await-in-the-array-functions/

No comments:

Post a Comment