Reputation: 171
I'm having issues after adding a work-around for CORS blocking a request within Create-React-App.
As recommended I have updated the proxy settings to the same domain I am trying to call in my package.json (example with dummy data)
"proxy": "https://jsonplaceholder.typicode.com"
and make the call in my App.js file as follows..
import React, { useState, useEffect } from "react";
function App() {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch("/posts/")
.then((res) => {
console.log(res.data);
})
.then((res) => setProducts(res.data));
});
return <div className="App">Returned here</div>;
}
export default App;
I don't get the CORS error anymore, which is good, however I do get the following error message
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
Tested the API in postman and its all returning correctly so not sure where the issue is.
Any help would be appreciated
Upvotes: 0
Views: 221
Reputation: 451
Code sandbox doesn't seem to be using create-react-app
out of the box.
From looking at the code:
fetch("/posts/")
.then((res) => {
console.log(res.data);
})
.then((res) => setProducts(res.data));
Should be adjusted to
useEffect(() => {
fetch("/posts")
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
setProducts(data);
});
}, []);
Upvotes: 1