TypeError when accessing videoId property in YouTube API v3 integration with RapidAPI

I’m working on building a YouTube clone app following a tutorial and ran into an issue with the YouTube v3 API through RapidAPI. My React component crashes when I try to render video items.

The problem happens when I use this conditional rendering: {video.id.videoId && <VideoItem data={video}/>}

Here’s my video list component:

import {Grid, Container} from '@mui/material';
import {ChannelItem, VideoItem} from './';

const VideoList = ({videoData}) => {

  return (
    <Grid container spacing={3} justifyContent="flex-start">
        {videoData.map((video, index) => (
            <Container key={index}>
                {video.id.videoId && <VideoItem data={video}/>}
            </Container>
        ))}
    </Grid>
  )
}

export default VideoList

This is the error I’m getting:

VideoList.jsx:9 Uncaught TypeError: Cannot read properties of undefined (reading 'videoId')
    at VideoList.jsx:9:1
    at Array.map (<anonymous>)
    at VideoList (VideoList.jsx:7:1)
    at renderWithHooks (react-dom.development.js:16305:1)

The app stops working completely after this error. How can I fix this undefined property issue?

The error occurs because some video objects in your array don’t have an id property at all, so when you try to access video.id.videoId, JavaScript can’t read videoId from undefined. I faced this exact same issue when working with the YouTube API through RapidAPI. The API sometimes returns different response structures depending on the search results. You need to add proper null checking before accessing nested properties. Try changing your conditional to {video.id?.videoId && <VideoItem data={video}/>} using optional chaining. This will prevent the component from crashing when the id property doesn’t exist on certain video objects.

I encountered a similar crash when integrating YouTube API through RapidAPI in my project last month. The issue stems from inconsistent data structures in the API response - some items might be channels instead of videos, which explains why video.id is undefined for certain entries. Beyond just using optional chaining, you should also filter your data before mapping to ensure you’re only rendering video items. Consider adding a check like video.id && video.id.videoId in your map function or filter the videoData array beforehand to remove non-video items. This approach prevents unnecessary rendering attempts and makes your component more robust against API variations.

had this exact bug last week! your videoData array probably has mixed content types from the api response. instead of just checking videoId, try adding video.id && video.id.videoId or use optional chaining like video.id?.videoId. the youtube api thru rapidapi sometimes returns channel data mixed with video data which breaks the rendering.