Amit Sharma
Amit Sharma

Reputation: 61

Not able to connect React App with a NodeJS in Backend

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}`));

enter image description here

Upvotes: 0

Views: 360

Answers (2)

Koala
Koala

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

Alpfreda
Alpfreda

Reputation: 397

Because your response is object not an array.

enter image description here

You can use map, filter and ... for array

Upvotes: 1

Related Questions