Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!