React Unable to access state property - Not found solution
Your collection
is being fetched after ComponentDidMount
and is an empty array at first. So you have to make sure collection
is defined before trying to access it like so:
{collection[0]? collection[0].artistName: null}
The issue is caused by the fact "collection" is an empty array prior to the getMusics request which is an async call. It takes time for the request to complete and your state to update.
It cannot find a value at collection[0] as it's undefined.
A simple solution would be to check the length of the collection array before returning your component, like so:
const { collection } = this.state;
if (collection.length === 0) {
return null;
}
Render is called before ComponentDidMount, also you are calling an asynchronous function.
So, just like jsNoob write:
<p data-testid="album-name">{collection[0]?.collectionName}</p>
<p data-testid="artist-name">{collection[0]?.artistName}</p>