I am currently trying out React for a future project and trying to get myself up to speed on it.
Bear with me, due to some circumstances I didn't code for 2 years so I am extremely rusty.
Anyway, I need to get React to properly fetch some data about tasks written up, but no matter what I try it just doesn't work. I have a function written as
getDataFromDb = () => {
fetch("http://127.0.0.1:8080/api/getTask")
.then(response => response.json())
.then(data => this.setState({ tasks: data.tasks, isLoading: false }))
.catch(error => this.setState({error, isLoading: false}));
};
Now my output inside the JSX file
<React.Fragment>
<h1>Random User</h1>
{error ? <p>{error.message}</p> : null}
{!isLoading ? (
tasks.map(task => {
const { title, description } = task;
return (
<div key={title}>
<p>Title: {title}</p>
<p>Desc: {description}</p>
<hr />
</div>
);
})
) : (
<h3>Loading...</h3>
)}
</React.Fragment>
No matter what I try with my own database, it just doesn't want to work with React. I try API calls through Postman and everything gets sent and received without any problems, but React sends out an error "Failed to fetch".
In my server.js I have the following api call written
router.get("/getTask", (req, res) => {
Task.find((err, task) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, task: task });
});
});
I have scoured Internet and Stack for some answers and examples, and, the dumbest thing is, if I use an external API (such as "https://hn.algolia.com/api/v1/search?query=redux"), or any other, honestly, then it works fine. If it makes any difference, I use mLabs sandbox for MongoDB.
Any suggestions? Been stuck on this for the last 5 hours or so.