hyun k
hyun k

Reputation: 191

Why does the problem occur even though post.Images [0] exists? TypeError: Cannot read property '0' of undefined

post.Images is output from the console.

console.log("post.Images " , post.Images);

output:

[{…}]
0: {id: 5, src: "dokyo11573054801107.png", createdAt: "2019-11-06T15:40:02.000Z", updatedAt: "2019-11-06T15:40:02.000Z", PostId: 14}
length: 1
__proto__: Array(0)

An error occurs in the code below

cover={post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}

error message: error message

but it's strange

post.Images [0] exists but undefine error is exists

I can't figure out what's causing it.

Thank you very much for letting me know

Thank you

github: https://github.com/hyunsokstar/ch6/blob/master/front/components/PostCard.js https://github.com/hyunsokstar/ch6

Upvotes: 0

Views: 48

Answers (2)

aldenn
aldenn

Reputation: 2280

I think, when you call PostCard and pass post into this Component, the post.Images data is undefined at the first time of render. So, in PostCard Component, the post.Images prop will be undefined.

I have two ways to resolve this issue:

  1. Try pass a default parameter like this:
const PostCard = ({ post = {} }) => {
   const { Images = [] } = post; 
   // If post.Images is undefined, default value always is an array

   cover={
      Images[0] && Images[0].src && 
      <img alt="example" src={`http://localhost:3065/${Images[0].src}` } />
   }
}
  1. Check if post.Images and post.Images[0] defined, then access to post.Images[0].src like this:
cover={
   post.Images && post.Images[0] && post.Images[0].src && 
   <img alt="example" src={`http://localhost:3065/${post.Images[0].src}` } />
}

Upvotes: 1

Rikin
Rikin

Reputation: 5473

During the initial render, Images may not be defined by that time, thus you can either create default [] in your local component or check if Images exists before accessing its value at position 0

cover={post.Images && post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}

Alternatively you can destructure from post like below and reduce your code as:

const { Images = [] } = post;

and your code snippet would change like below:

cover={Images.length && <img alt="example" src={`http://localhost:3065:/${Images[0]}` } />}

Upvotes: 1

Related Questions