Search code examples
javascriptreactjsruntime-error

TypeError: Cannot read properties of undefined reading 'length'


I'm getting this error within the equipmentExercises block while fetching the data from the API. I have already checked the datatype which is an array. And equipmentExercises.length is showing an undefined datatype.

const SimilarExercises = ({ targetMuscleExercises, equipmentExercises }) => {
    console.log(equipmentExercises);
    return (
        <Box sx={{ mt: { lg: '100px', xs: '0px' } }}>
            <Typography
                sx={{ fontSize: { lg: '44px', xs: '25px' }, ml: '20px' }}
                fontWeight={700}
                color="#000"
                mb="33px"
            >
                Similar <span style={{ color: '#FF2625', textTransform: 'capitalize' }}>Target Muscle</span> exercises
            </Typography>
            <Stack direction="row" sx={{ p: 2, position: 'relative' }}>
                {targetMuscleExercises.length !== 0 ? <HorizontalScrollbar data={targetMuscleExercises} /> : <Loader />}
            </Stack>

            <Typography
                sx={{ fontSize: { lg: '44px', xs: '25px' }, ml: '20px', mt: { lg: '100px', xs: '60px' } }}
                fontWeight={700}
                color="#000"
                mb="33px"
            >
                Similar <span style={{ color: '#FF2625', textTransform: 'capitalize' }}>Equipment</span> exercises
            </Typography>
            <Stack direction="row" sx={{ p: 2, position: 'relative' }}>
                **{equipmentExercises.length !== 0 ? <HorizontalScrollbar data={equipmentExercises} /> : <Loader />}**
            </Stack>
        </Box>
    );
};

Solution

  • This is because your equipmentExercises and targetMuscleExercises might be null at first place.

    You can fix this by adding a check like this: equipmentExercises?.length !== 0 or equipmentExercises && equipmentExercises.length !== 0