I'm a beginner in Reactjs, I'm working on a react project which uses an API I want the component to be functional but when I make it a functional component it gives me the following error:
TypeError: Cannot read property 'map' of undefined
here is my component projects.component.jsx
:
import React, { useState, useEffect } from "react";
function Projects() {
const [projects, setProjects] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/api/projects/")
.then((res) => {
res.json();
})
.then((res) => {
setProjects(res);
})
.catch(err => console.log(err))
}, []);
return (
<div>
<h2>
{projects.map((project) => (
<div className="notes" key={project.id}>
<h1>{ project.title }</h1>
</div>
))}
</h2>
</div>
);
}
export default Projects;
and here is my app.js:
import "./App.css";
import Projects from "./components/projects.component";
import { Route } from "react-router-dom";
function App() {
return (
<div className="App">
<Route path="/" component={Projects} />
</div>
);
}
export default App;
How can I fix the error of map being undefined?