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
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) :
Or you can do this if the value of data.result can be null :
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.
));
By adding joke?, you are stating that if there is a joke data, then execute this.
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