1

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.

  • 3
    A `console.log` directly after setting state will log the current state value, not the updated value. React guarantees (barring mutation) that a state value is consistent throughout a render cycle with updated values only available on the next cycle. see: [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – pilchard May 15 '22 at 19:51
  • Put a `console.log(data)` inside the `.then()` callback instead. You've never waited for the `fetch` to complete – Bergi May 16 '22 at 00:30

1 Answers1

0

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 i.e when its resolved.

Usama Masood
  • 141
  • 5