Firebase Delay When Retrieving Data
Using the Firebase API to read data from the database gives me an awkward moment of things just suddenly coming to place 1-2 seconds after web UI has loaded. Does anyone have any a
Solution 1:
below is a simple example to fetch the user status on firebase
const app = firebase.initializeApp()
const db = app.database();
let unsub;
const user = newPromise((resolve, reject) => {
unsub = app.onAuthStateChanged(
status => {
if ( status === null ) {
resolve(app.signInWithEmailAndPassword());
} elseresolve(user);
},
err =>reject(err);
)
});
user.then(unsub, unsub);
db.ref("path/to/data").on("child_added", () => {});
// this promise will fail if the user is not// authconst data = db.ref("path/to/data").once("value");
You don't have to wait for this promise to be settled to open subscription. However depending of your app's settings your database cannot be read if you are not authenticated.
So a solution can be pretty straighforward.
With a little bit of refactor we have :
constgetData = () => db.ref("path/to/data").once("value");
user.then(getData).then(data => { /* data here */ });
This last promise will effectively be resolved as soon as the user is auth once if and only if everything went ok. You can open the subscription before authenticating the user but it is not guarenteed to go faster. The only way to beat it is by simply removing the reading rights needed to access the db in the first place...
Post a Comment for "Firebase Delay When Retrieving Data"