0

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?

zain
  • 416
  • 5
  • 19

1 Answers1

1

The issue is in your first .then() chain - the function is not returning the res.json() result so you end up setting projects to undefined:

    useEffect(() => {
        fetch("http://127.0.0.1:8000/api/projects/")
            .then((res) => {
                res.json();
              //^^^^^^^^^^^ problem is here - the json value is not being returned here
            })
            .then((res) => {
                 //^^^ so res is now undefined
                setProjects(res);
            })
            .catch(err => console.log(err))
    }, []);

The solution is to either return the result:

.then((res) => {
    return res.json();
})

Or remove the wrapping curly braces {} to allow the implicit return behaviour of arrow functions:

.then((res) => res.json())

For more information on how syntax differences change arrow function behaviour, see the mdn Arrow functions documentation page.

Regarding braces and implicit return, see the Function body section.

Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50