unable to fetch data, it gave me an error that apiData is not a function. Could not understand what’s the issue. Can anyone help?
const Mission = () => {
const [apiData, setList] = useState([]);
const [rocketData, setRocketData] = useState(null);
const fetchData = async () => {
try {
const res = await fetch("https://api.spacexdata.com/v3/missions/F3364BF");
if (!res.ok) {
throw new Error("Network response was not ok");
}
const data = await res.json();
setList(data);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
fetchData();
}, []);
const handleClick = (mission) => {
setRocketData(mission);
};
return (
<div>
{apiData.map((mission, index) => (
<div key={index} onClick={() => handleClick(mission)}>
<p>{mission.mission_name}</p>
<p>{mission.mission_id}</p>
<p>{mission.description}</p>
</div>
))}
</div>
);
};
export default Mission;
I tried some other variations but not luck.
Hope someone can help, thanks in advance.
2
Answers
The problem is from the api url that you have passed into
fetch
. The current api returns a single mission object. You’re getting the error because you’re callingmap
on an object. If you want to fetch all the missions you should change your api url to:This should fix your issue.
apiData is not a function," occurs because apiData is an array state, not a function. However, in your code, the issue lies in how you’re trying to use apiData.
Make sure that the data you’re trying to fetch is actually an array, or adjust the state handling accordingly.
and Rename setList to setApiData for clarity.
corrected version of your component.