As a newcomer to React and API usage, I am facing difficulty resolving the error below. My goal is to showcase a carousel of images using React.js but encountered this issue:
Error message: Popular.jsx:26 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
In addition to the above error, another error message appears:
The provided error originated in the following component: Popular (http://localhost:3001/static/js/bundle.js:120:80) within div under Home within div under Pages within div under App Consider incorporating an error boundary into your codebase for customized error handling. Go to https://reactjs.org/link/error-boundaries to gain insights on error boundaries.
I would appreciate any guidance on how to resolve this issue as my attempts via YouTube and Google have not led to a solution.
Here's a snippet of my code:
import { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Splide, SplideSlide } from '@splidejs/react-splide';
import '@splidejs/splide/dist/css/splide.min.css';
function Popular() {
const [popular, setPopular] = useState([]);
useEffect(() => {
getPopular();
}, []);
console.log(process.env.REACT_APP_API_KEY);
const getPopular = async () => {
const api = await fetch(
`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`
);
const data = await api.json();
setPopular(data.recipes);
};
return (
<div>
<Wrapper>
<h3>Popular Picks</h3>
<Splide
options={{
perPage: 4,
arrows: false,
pagination: false,
drag: 'free',
gap: '5rem'
}}
>
{popular.map((recipe) => {
return (
<SplideSlide>
<Card>
<p>{recipe.title}</p>
<img src={recipe.image} alt={recipe.title} />
</Card>
</SplideSlide>
);
})}
</Splide>
</Wrapper>
</div>
);
}
const Wrapper = styled.div`
margin: 4rem 0rem;
`;
const Card = styled.div`
min-height: 25rem;
border-radius: 2rem;
overFlow: hidden;
position: relative;
img{
border-radius: 2rem;
position: absoute;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
p{
position: absolute;
z-index: 10;
left: 50%;
bottom: 0%;
transform: translate(-50%, 0%);
color: white;
width: 100%;
text-align: center;
font-weight: 600;
font-size: 1rem;
height: 40%;
display: flex;
justify-content: center;
align-items: center;
}
`;
export default Popular;
Your assistance is highly appreciated!