Home > Mobile >  Not able to connect React App with a NodeJS in Backend
Not able to connect React App with a NodeJS in Backend

Time:09-09

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

CodePudding user response:

Because your response is object not an array.

enter image description here

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}</>;
  • Related