Resolving Uncaught TypeError in React when trying to read properties of undefined (specifically 'map')

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!

Answer №1

By initializing your state with an empty array, you are ensuring that .map will not throw any errors.

If you suspect an issue with your API key/call/response, try logging the response after this line: const data = await api.json();.

For example, without a key, calling the API results in the following response:

  { 
    status: "failure", 
    code: 401, message: 
    "You are not authorized. Please read https://spoonacular.com/food-api/docs#Authentication" 
  }

If there is an error and you call setPopular(data.recipes);, it is equivalent to saying setPopular(undefined). Subsequently, undefined.map(...) will trigger an error.

To avoid such errors, consider checking whether popular is truthy.

In the render method, modify {popular.map((recipe) => { to

{popular && popular.map((recipe) => {

If you want to ensure no errors occur, verify if popular is an array:

{Array.isArray(popular) && popular.map((recipe) => {

You can implement a similar approach to render a different component when there is no data available:

  if (popular) {
    <SplideSlide>...</SplideSlide>
  } else {
    <NoSlidesAvailableComponent />
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to resolve the issue "Error: no valid exports main found" specifically on a Windows 7 operating system?

I've been encountering an issue while attempting to run my react app on Windows 7 OS. I have npm version 6.13.4 and node version 13.6.0 installed on my system. Every time I try to start the application using npm start, I receive the following error co ...

Guide to creating a menu item that redirects to a link with the use of href

I am currently working with MenuItem provided by the material-ui library. My objective is to open a link in a new tab when the menu item is clicked. The approach I have taken so far is utilizing the following code snippet: <MenuItem href="www.googl ...

What is the CSS method for determining the distance from the top of a container to the edge of the window?

I am working on a basic HTML layout that contains a few elements, including a scrollable div container located below them. Since the height of unknown-height is uncertain due to dynamic element generation, I need a simple method to enable scrolling in the ...

Integrate attributes from several personalized hooks that utilize useQuery with secure data typing in React Query

I am currently facing a challenge where I have multiple custom hooks that return query results using useQuery. My goal is to combine the return values from these hooks into one object with the following structure: { data, isLoading, isFetching, isS ...

Nested styles container in JSS

While working with the React Material UI component TextField, I encountered a need to create a wrapper around it that allows for easy styling overrides. According to the documentation, there are two props that can help achieve this: 1) InputProps - This pr ...

Creating consistent image sizes in Bootstrap

I'm currently using Bootstrap 4 to showcase multiple images on my website. I have attempted to apply the Grid system as per Bootstrap's guidelines, but the display of the images is not aesthetically pleasing due to their uneven sizes, which can b ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

Setting up automatic CSS linting in a Vue.js project for seamless correction

Is there a way to enforce linting on the <style> segment within a .vue file while coding? I have set up eslint (with airbnb ruleset)+prettier for the <template> and <script> sections, which includes some auto-correction upon saving, but I ...

Can you explain the significance of the ColSpan property in the Material UI TablePagination?

Why is ColSpan used in this code snippet? Reference: https://material-ui.com/components/tables/#table Check for the arrow symbol <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, ...

Placing an Image in the Right Corner Using jQuery Mobile

I am currently developing a mobile app and I need to align three images one below the other at the right corner next to some text. Any suggestions would be greatly appreciated. Thank you in advance. Below is my code snippet: <div> <ul data-r ...

Encountering an issue with the installation of react-twitter-embed

Having an issue with react-twitter-embed. I encountered an error when running the command: install error If anyone has a solution to this problem, please share it with me. ...

Ways to link my frontend to a NodeJS backend that is publicly deployed rather than on localhost

When my NodeJS server is running on localhost PORT, I can successfully connect them both by using the following code: const PORT = 9000; const app = express() app.listen(PORT, () => console.log(`Server is up and running on PORT ${PORT}`)) app.use(bodyPa ...

Creating separation between a dropdown menu and its corresponding button

I'm dealing with a situation where I have a button that reveals a hidden droplist upon hover. The problem is that there is no space between the button and the droplist, causing interference with the functionality. My attempt to create some distance b ...

JavaScript - Reveal a div when a grid item is clicked

I have created a grid with a 5x7 layout using divs. I am trying to achieve a feature similar to the Netflix interface where, upon clicking on a div, a larger div will appear beneath it. This larger div should expand to 100% width of the parent container, p ...

Text input field with uneditable text displayed at the end

Click here to view the input field I am looking to create an input field that always displays a "%" at the end of the input. Here is what my react component looks like currently: <StyledBaseInput type="text" ...

MUI enables the creation of a fixed vertical box anchored at the bottom of the screen

I’ve attempted the following so far: import "./styles.css"; import { Box, Typography } from "@mui/material"; import styled from "@emotion/styled"; export default function App() { const MainStyle = styled("div")(( ...

Is it possible to nest HTML within a Route component?

<Router> <Routes> <Route path='/' element={<Navbar />} /> <Route path='/' element={<div className='recipes'> {query ? query.map((object, i) => ( <Recipe ...

Unusual Occurrence: Unexpected Gap at the Beginning of HTML

There seems to be an issue with white space appearing unexpectedly at the top and right side of the file in a website I am working on. Despite adding margin: 0; padding: 0; to both <body> and <html>, the problem persists. After inspecting the ...

Bootstrap 3 Implementation of a Clear Navbar

I'm trying to create a transparent navbar using the code below: <div class="navbar navbar-default navbar-fixed-top" style="top:50px; background:transparent;"> <div class="navbar-inner"> <div class="container"> <ul cla ...

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...