So I've been trying to figure this one out for a while and I'm really hoping someone would be able to help
I'm creating an array and storing a list of objects in it like this.
const heroPost = postList.filter(post => post.hero);
when I console log heroPost I get the following result.
I'm trying to access the url property in this object as follows.
console.log(heroPost[0].url);
But I keep getting this undefined error.
I'm not really sure what's going wrong here. I am using an async function to get data from a database which I'm guessing might be a problem but I'm outputting data from the 'postList' in jsx which I've used to retrieve data into the 'heroPost' so I'm uncertain how it can be the problem. Any help or ideas would be greatly appreciated.
Thank you!
Edit: This is the portion of the component that uses the 'postList' to render data. Which works fine.
<div className="posts-container">
{postList.map((post) => (
<div key={post.id} className="post">
<h3 className="post-title">{post.title}</h3>
<div className="post-info">
<p className="author">{post.author}</p>
<p className="timestamp">{post.author}</p>
</div>
<p className="content">{post.body}</p>
<img src={post.url} alt="" />
</div>
))}
</div>
What I'm trying to do now is to use the heroPost to render data into the hero section of the page as follows but it is still throwing the undefined error.
<div className="hero">
<img src={heroPost[0].url} alt="" />
</div>
Thank you for all the comments and answers, I understand the problem now. Still don't really get why it works in the 'postList' instance and not here. Is there a way I can do this without directly trying to go to the file where I retrieve the data and add it into that function?
CodePudding user response:
Since you are using an async function to get the data, when the component that consists this code, renders for the first time, it will not have the data it needs to render the component.
Hence 'undefined'
You can resolve this issue by conditionally rendering the component. That is, render the component only after the data is available.
Since you haven't shared the component code, you can refer this react doc to help with the issue :
For the second snippet you shared:
<div className="hero">
{(heroPost && heroPost[0])?<img src={heroPost[0].url} alt="" />:'No data'}
</div>
CodePudding user response:
Simple answer: you get those error because it's undefined
If you look at you console.log
you can see an empty array at the first line
That's because when you first render your component postList
is an empty array.
Only after you fetch your data and populate you array you can access it
you can try to do this
useEffect(() => {
setHeroPost(postList.find(p => p.hero))
}, [postList])