0

I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed.

Please see the code below.

REACT

Home.js (this is the code for products)

const loadAllProducts = () => {
  getProducts()
    .then((data) => {
      if(data.error) {
        setError(data.error); //box filled with data error
        console.log(error); // message "error"
      } else {
        setProducts(data); // box filled with data product
      }
    });
    loadAllProducts();
};

coreapicalls.js (here I want to fetch the data)

import { API } from "../../backend.js";
export const getProducts = () => {
  return fetch(`${API}product`, { method: "GET" })
   .then(response => response.json())
   .catch((err) => console.log(err));
  };

.env (I have both of my servers running, the url and symbol "/" are correct.)

REACT_APP_BACKEND = http://localhost:8000/api/

My compiler returns no specific error. ./src/core/Home.js Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars ./src/core/Card.js Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars

DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/)

'api',
'api.category',
'api.product',

Best, Rok.

r_hribar
  • 11
  • 2
  • "My compiler returns no specific error", the error description is very specific and is telling you exactly what the problem is. – Sam R. Sep 16 '20 at 16:14
  • I have moved the loadAllProducts outside. And written this: useEffect(loadAllProducts, [] ) . As per this thread https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook . Now I have this problem "Unhandled Rejection (TypeError): data is undefined". – r_hribar Sep 16 '20 at 19:52

1 Answers1

0

I went into chrome devtools and saw a "cors error" under network. I forgot to run "pip install django-cors-headers" . The configuration on the DJANGO REST API for corsheaders was correct.

r_hribar
  • 11
  • 2