skip to Main Content
import React, {
  useState,
  useEffect
} from 'react';


export default function App() {
  // State to hold the array of results
  const [joke, setJoke] = useState([]);


  useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=10")
      .then(res => res.json())
      .then(data => setJoke(data.results))
      .catch(error => console.error(error));
  }, []);


  // Map over the results and create JSX elements
  const jokeElements = joke.map((item, index) => (<h2 key={index}>{item.question}</h2>));

  return (<div>{jokeElements}</div>);
}

It is giving me an issue of
Cannot read properties of undefined (reading ‘map’)
How can I fix that it won’t show this issue anymore?

3

Answers


  1. It is possible that the data.result value is not an array, so you cannot map on it

    You can add Elvis Operator (optional chaining) :

    const jokeElements = joke?.map((item, index) => (<h2 key={index}>{item.question}</h2>));
    

    Or you can do this if the value of data.result can be null :

    useEffect(() => {
        fetch("https://opentdb.com/api.php?amount=10")
          .then(res => res.json())
          .then(data => setJoke(data.results || []))
          .catch(error => console.error(error));
      }, []);
    
    Login or Signup to reply.
  2. I think your error has to do with the useEffect. When the joke.map line is executed, the joke state might still be an empty array, causing the "Cannot read property ‘map’ of undefined" error.

    See if doing some operational chaining helps.

      const jokeElements = joke?.map((item, index) => (
    <h2 key={index}>{item.question}</h2>
    

    ));

    By adding joke?, you are stating that if there is a joke data, then execute this.

    Login or Signup to reply.
  3. The reason you are encountering this error is that when the component initially renders joke is a completely empty array that doesn’t have any item to map over. A fix to this is to check that the array isn’t empty before mapping over it

    
    import React, { useState, useEffect } from "react";
    
    export default function App() {
      // State to hold the array of results
      const [joke, setJoke] = useState([]);
    
      useEffect(() => {
        fetch("https://opentdb.com/api.php?amount=10")
          .then((res) => res.json())
          .then((data) => setJoke(data.results))
          .catch((error) => console.error(error));
      }, []);
    
      // Map over the results and create JSX elements
      const jokeElements =
        joke.length > 0 ? ( // check if the array has an existing item
          joke.map((item, index) => <h2 key={index}>{item.question}</h2>)
        ) : (
          <div>Empty</div>
        );
    
      return <div>{jokeElements}</div>;
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search