import React from "react";
const VideoDetails = ({ info }) => {
const { snippet, statistics } = info;
console.log(snippet);
return (
<div>
<h1>{snippet.title}</h1>
</div>
);
};
export default VideoDetails;
Hi everyone,
I have pasted the code in which I’m facing the issue. Here I can easily console.log the "snippet and statistics", which are children of info props. But there are children in the "snippet" too. When I’m trying to access the child of "snippet/statistics", I’m getting the value for the first run of code. When I’m refreshing the page then I’m facing an error as shown.
I’m not able to understand if I can log "snippet" then why can’t I use the children present in "snippet".
"snippet" console output –
{publishedAt: ‘2024-04-18T04:10:49Z’, channelId: ‘UCl_vAxZpvbO-PFXdDu7EdHw’, title: ‘I JOINED A BIG GANG IN NEW GANGSTER CITY’, description: ‘Join the Best GTA RP Server Grand RP!!!nhttps://gt…here I post gaming videos & live stream everyday.’, thumbnails: {…}, …}
I have added just tag below the video to get the video title (snippet.title
). And it is reflected in the UI. As soon as I hit the refresh I’m facing the error as shown in the image above. But if I’m not accessing the "title" element then even after multiple refreshes I’m able to see the console.log and the object data inside it, even "title" is also showing in the console, but I don’t know why it’s not accessible.
2
Answers
set default value for
info
or
use condition for check exist
snippet
andsnippet.title
From the dev tools console pane, I can see
undefined
logged 2 times, so I’m assuming you are getting this data from a network call(a response that is resolved asynchronously).Since you are trying to access a property on an object that is
undefined
you are getting the error. Although the data may be available later, since the application has already crashed it cannot render the latest value.To fix this, do not execute
snippet.title
or try to access any property onsnippet
prop, when the value ofsnippet
is still undefined.You can use optional chaining to avoid the above error. Or, render some placeholder data like a loading text or something similar until the data is available.