I’m trying to call simple apiCall in react js but this is giving error as given below:-
data.map is not a function
My Code:-
import "./styles.css";
import React, { useEffect, useState } from "react";
export default function App() {
const [data, setData] = useState();
const apiCall = () => {
fetch("https://fakestoreapi.com/products/1")
.then((res) => res.json())
.then((json) => {
setData(json);
console.log(data);
});
};
useEffect(() => {
apiCall();
}, []);
return (
<div className="App">
{data
? data.map((val) => (
<div>
<h2>{val.id}</h2>
</div>
))
: ""}
</div>
);
}
Thanks for your efforts!
3
Answers
Because the data return from API is an
Object
, and there is nomap
method for the object, you can useObject.entries
,Object.values
,Object.keys
to iterate over an object.The data you’re getting from
https://fakestoreapi.com/products/1
is an object, not array. You cannot only applymap
method on an Object. Read about map hereI edit your code to :
you get this error because data is a
object
not an array