简体   繁体   中英

useEffect returning different values in React

I have an API asking for a query in PostgreSQL, so I have this:

const getPresupuestos = () => {
    return new Promise(function(resolve, reject) {
      pool.query('SELECT * FROM presupuestos ORDER BY id ASC;', (error, results) => {
        if (error) {
          reject(error)
        }
        resolve(results.rows);
      })
    }) 
}

And then in the index have this:

app.get('/', (req, res) => {
  bd.getPresupuestos()
  .then(response => {
    res.status(200).send(response);
  })
  .catch(error => {
    res.status(500).send(error);
  })
})

The problem is that I have a react app from where I'm trying to get the value of the query as a string with this code:

    const [presupuestos, setPresupuestos] = useState(false);
    useEffect(() => {
      getPresupuestos();
      console.log(presupuestos) //return in console
    }, []);
    function getPresupuestos() {
      fetch('http://localhost:3001')
        .then(response => {
          return response.text();
        })
        .then(data => {
          setPresupuestos(data); //value wanted
        });
    }

And the first time I execute this, the console.log returns the query I want, but if I refresh the page I get a false from the same console.log .

I'm quite new to React, so I would be grateful if someone could tell me why is this happening and how to get the value that I need.

As your function getPresupuestos is updating the state after resolving the promise, which might take some time and you won't be able to get its value right after it. What you could do is log the data in then of promise ie when its resolved.

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