简体   繁体   中英

Using Fetch in React to fetch data from server

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!!

TL;DR

There's a mistake in how you use arrow functions' implicit returns in your server side code.

The fix is to just add a return total; in the first .then(...) handler.

Details

First off, let's get it out: I agree with the comments on not neglecting error checks! (Be it fetch or anything else.)

Anyway: You use arrow functions in your .then(...) handlers. But that last statement in the first one is console.log(total) . The return value of that call is undefined , which becomes the implicit return value of your arrow function. The promise then passes this on as the value of response in your second .then(...) handler. (You could verify that by adding console.log(response) in the second .then(...) handler.

The fix is to just add a return total; in the first .then(...) handler:

const handleNumberOfJobs = (req, res, Register) => {
  Register
    .find({})
    .then(users => {
      const total = users.reduce(
        (sum, { numberOfJobs }) => sum + 
            numberOfJobs, 0
      );
      console.log(total);   // <-- returns undefined
      return total;         // <-- pass on to next promise
    })
    .then(response => {
      // console.log(response);  // if you're curious
      res.json(response)
    })
  }
}

Personal hint: Indent / lint your code for easier maintenance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM