I am trying to fetch data from the server(Node.js) with the following code:
componentDidMount = () => {
fetch('http://localhost:3000/numberofjobs')
.then(response => response.json())
.then(numberOfJobs => {
console.log(numberOfJobs)
})
}
That's my route in Node:
const handleNumberOfJobs = (req, res, Register) => {
Register.find({})
.then(users => {
const total = users.reduce((sum, { numberOfJobs }) => sum +
numberOfJobs, 0);
console.log(total);
})
.then(response => res.json(response))
}
One problem I'm having is the Front-end console.log is not showing up in the console, and I don't know why. In the server side, when the pages loads it does console.log the sum and everything, so it's working so I believe I am doing something wrong with React. I want to bring this info to my front-end so I could display it on the page.
Thanks a lot!!
fetchcall. This is such a common mistake that I wrote it up on my anemic little blog.fetch, which isn't likely to be the problem, that looks fine other than it's a bit unusual to makecomponentDidMountan arrow function like that. Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the[<>]toolbar button). Stack Snippets support React, including JSX; here's how to do one. (You can usesetTimeoutto simulatefetch.).catch(error => console.log(error)). It's likely throwing an error somehow and not reaching the console.log you have in your.then..then(response => res.json(response))would return response. I think returning response (res.json(response)) in the firstthen, where you haveconsole.logwould work.