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}`));
CodePudding user response:
Because your response is object not an array.
You can use map, filter and ... for array
CodePudding user response:
Seems like you are mapping a non-list data.
const [fetchData, setFetchData] = useState([]);
useEffect(() => {
fetch("/api")
.then((res) => res.json())
.then((data) => {
setFetchData(data);
});
}, []);
return <>{fetchData.q1.whateverIsNext}</>;