Omar
Omar

Reputation: 81

Promise returned from fetchData is ignored

I'm not sure what the problem is. I understand axios isn't able to get a response from the api but I cannot understand why.

My nodejs backend server file:

import data from './data';

const app = express();
app.get("/api/products", (req, res) => {

    res.send(data.products);
})
app.listen(5000, () => {console.log("Server started at http://localhost:5000")})

I can see the data on localhost:5000 but not when I try to render it in the frontend. I get an error saying "cannot get api/products"

Frontend api call:

const [products, setProducts] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const { data } = await axios.get("/api/products");
            setProducts(data);
        }
        fetchData();
        return () => {
            //
        };
    }, [])

package.json in the frontend:

{
  "name": "frontend",
  "proxy": "http://127.0.0.1:5000",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

network logs: enter image description here

Upvotes: 3

Views: 5447

Answers (1)

Jumshud
Jumshud

Reputation: 1425

fetchData returns Promise. you need to resolve it by using await or then. And you need to extract your method from the useEffect hook:

const fetchData = async () => {
   const { data } = await axios.get("/api/products");
   return data;
}

useEffect(() => {
    fetchData().then(data => setProducts(data));
}, []);

Upvotes: 3

Related Questions