Reputation: 61
I am trying to fetch data from backend but getting error fetchData.map is not a function
.
If can anyone explain me why fetchData.map is not a function
This is react code
function App() {
const [fetchData, setFetchData] = useState([]);
useEffect(() => {
fetch("/api")
.then((res) => res.json())
.then((data) => {
console.log(data);
setFetchData(data);
});
}, []);
return <>{fetchData.map(data=> <div>data</div>)}</>;
}
This is NodeJS code
const express = require("express");
const app = express();
const test = require("./test.json");
PORT = 3001;
app.get("/api", (req, res) => {
res.json(test);
});
app.listen(PORT, () => console.log(`Server Started on ${PORT}`));
Upvotes: 0
Views: 360
Reputation: 462
function App() {
// Change it to null by default
const [fetchData, setFetchData] = useState(null);
useEffect(() => {
fetch("/api")
.then((res) => res.json())
.then((data) => {
console.log(data);
// wrap data with [] to make it iterable
setFetchData([data]);
});
}, []);
// Check if value is present before mapping
return <>{fetchData?.map(data=> <div>data</div>)}</>;
}
Upvotes: 1
Reputation: 397
Because your response is object not an array.
You can use map, filter and ... for array
Upvotes: 1