I have an endpoint as http://localhost:8000/news and I am using in it a react project. I have tested it on Postman and it fetches fine. But I get an empty array when I console.log the data.
Please can anybody look through the code and tell me what I am getting wrong?
A Quick side note - there is no cors error displayed on the browser console.
Here is my code below:
const App = () => {
const [data, setData] = useState([]);
const [pending, setPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('http://localhost:8000/news')
.then((response) => {
if (!response.ok) {
throw 'News could not be fetched at the moment';
}
return response.json();
})
.then((news) => {
setData(news.data);
setError(null);
setPending(false);
})
.catch((error) => {
setError(error.message);
setPending(false);
});
}, []);
console.log('Data', data);
return (
<BrowserRouter>
<Navbar />
<Container maxWidth="lg">
{error && <div>{error}</div>}
{pending && <div>Loading</div>}
<Switch>
<Route exact path="/">
<Posts data={data} />
</Route>
<Route path="/news/:id">
<PostDetail />
</Route>
<Route path="/create">
<CreateNews />
</Route>
</Switch>
</Container>
</BrowserRouter>
);
};
export default App;
question from:
https://stackoverflow.com/questions/65951210/react-fetch-returns-an-empty-array-with-no-cors-error 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…