-1

I want to save query result to global variable.

I'll use global variable data on ReactNative using Chart.js.

How can I do? Is there any other way?

var query = "select * from hepi;";

var data;

db.all(query, [], (err, rows) => {
    if (err) {
      throw err;
    }
    data = rows;
    
});

console.log(data); // undefined. I can't use variable for Chart.js
Ssss
  • 1
  • 2
  • Do not try to store it to a global variable, write the code that uses it inside the callback. Global variables are usually bad, especially when doing asynchronism. – Guerric P Jun 04 '21 at 14:08
  • It *is* assigning it to `data` but only after the `console.log()` call. – pilchard Jun 04 '21 at 14:10

1 Answers1

0

That db.all is asynchronous. It means that the code inside the callback is not immediately called (for example, connecting to the db and retrieving the query can take time).

So, here's what's happening:

You define a var data, then you query the db but the results are not retrieved synchronously. So, the console.log is executed, obviously printing undefined. You have to move that console.log (and every other code you want to run with data) inside the callback, or you can use promises.

Andrea Roveroni
  • 184
  • 1
  • 6