Advertisements
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!
>Solution :
Because the data return from API is an Object
, and there is no map
method for the object, you can use Object.entries
, Object.values
, Object.keys
to iterate over an object.
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 ? Object.entries(data).map(([key, value]) => <div><span>{ key }:</span><span>{ JSON.stringify(value) }</span></div>) : null
}</div>;
}