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.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/sDfgRLU
Comments
Post a Comment