How to Access Firebase Variable Outside Firebase Function

How can i access firebase variable outside firebase function

Agreed with Jay's comment. You cannot return the status like that because Firebases works asynchronously... what I would do, is add a closure parameter that executions on completion like so:

class signUpClass:UIViewController {

// check to see if form is empty

let ihelpController = UIViewController()
var CurrentStatus:status!

func signUp(var formArray: [String:String], complete:(CurrentStatus)->()){

var formStatus:status = ihelpController.checkIfFormIsEmpty(formArray)

if (formStatus == status.success){
//form is ok to process
// check DOB
//TODO: create date calculation function

let DateOfBirth:Int = 18

if DateOfBirth < 18 {
//user is not 18 they can not register
alertError("oops", message: "You must be 18 to register", comfirm: "Ok")

} else {
//Proceed with registration
let firebaseController = Firebase()
var email = "asdf@afd.com"
var password = "1234"

firebaseController.refPath("users").createUser(email, password: password, withValueCompletionBlock: {error, result in

if error != nil {
print("registration Error")
self.alertError("oops", message: "That email is registered already", comfirm: "OK")

} else {
let vc =
print("user can register")
firebaseController.firebaseRefUrl().authUser(email, password: password, withCompletionBlock:{
error, authdata in

if error != nil {

print("login Error")
}else{

let userId = firebaseController.firebaseRefUrl().authData.uid

formArray["userId"] = userId

firebaseController.refPath("users/\(userId)").updateChildValues(formArray)
print("user is register and can proceed to dashBoard")

//Send status to callback to handle
complete(status.success)
}
})
}
})
}
}
}

Access Firebase variable outside Closure

Firebase is asyncronous and the data is only valid when it's returned from Firebase within the closure.

 FIRDatabase.database().reference(withPath: "data").child("numCells")
.observeSingleEvent(of: .value, with: { snapshot in
if let snapInt = snapshot.value as? Int {
self.navigationItem.title = String(snapInt)
}
})

Expanding from that, suppose we want to populate an array to be used as a dataSource for a tableView.

class ViewController: UIViewController {
//defined tableView or collection or some type of list
var usersArray = [String]()
var ref: FIRDatabaseReference!

func loadUsers() {
let ref = FIRDatabase.database().reference()
let usersRef = ref.child("users")

usersRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot {
let userDict = child as! [String: AnyObject]
let name = userDict["name"] as! string
self.usersArray.append[name]
}
self.myTableView.reloadData()
})
}
print("This will print BEFORE the tableView is populated")
}

Note that we populate the array, which is a class var, from within the closure and once that array is populated, still within the closure, we refresh the tableView.

Note that the print function will happen before the tableView is populated as that code is running synchronously and code is faster than the internet so the closure will actually occur after the print statement.

Cant access variable inside of firebase gotData() function outside

The reason you don't get the value on the last line is because it is asynchronous. Basically you do ref.on and it runs the gotData() function if (and more importantly WHEN) it is successful, but your last console.log() runs regardless of whether gotData() is finished.

An easy way to handle this is by defining a separate function which takes power_level as a parameter and handles the power_level, and run that at the end of gotData().

Something like this:

var config = {
//
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("power");
ref.on("value", gotData, errData);

var power_level;
function gotData(data) {
var power = data.val();
// Grab the keys to iterate over the object
var keys = Object.keys(power);
console.log(keys);
for (var i = keys.length-1; i < keys.length; i++) {
var key = keys[i];
// Look at each fruit object!
var power_level = power[key];
console.log(power_level);

////////// call handlePowerlevel here to handle logic further
handlePowerlevel(power_level)
}
}

function handlePowerlevel(pl) {
console.log(pl);
// actual logic
}

How to pass a variable from outside the function to a firebase event

If the two operations are within the same file you can just wrap the Twilio call in a function and call it from within the Firebase operation like so...

function sendSMS(dest, msg) {
client.messages.create({
to: dest,
from: "+14352058756",
body: msg
}, function(err, message) {
console.log(message.sid);
});
}

ref.limitToFirst(1).on('child_added', function(snapshot) {
var userDetails = snapshot.val();
var mobileNumber = userDetails.mobileNumber;

sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});

If the Twilio operation is in a different file, you can export it and require where you use Firebase

//twiliofile.js
module.exports.sendSMS = function(dest, msg) {
client.messages.create({
to: dest,
from: "+14352058756",
body: msg
}, function(err, message) {
console.log(message.sid);
});
}

-

//firebasefile.js
var sms = require('./twiliofile.js');

ref.limitToFirst(1).on('child_added', function(snapshot) {
var userDetails = snapshot.val();
var mobileNumber = userDetails.mobileNumber;

sms.sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});

(ReactAssign firebase snapshot to a variable outside of the function

Switch the anonymous function that you're passing to .then to an arrow function to allow you to use the this from the class scope.

Plenty of information elsewhere on this

Use local variable outside the function with dart


Future<List<String>>getC() async {
List<String> idList=[];
await Usersref.where("email", isEqualTo: widget.list['email'])
.get()
.then((QuerySnapshot snapshot) {
snapshot.docs.forEach((document) {
print(document.id);
idList.add( document.id);

});

});
return idList;
}

Firebase - retrieving data by value to an outside variable

Firebase use callback methods to get the data from the server, In your case the return statement will be executed before the callback come from the Firbase. You can try to pass a callback method to your function and execute that when the callback from Firebase is triggered.

public static void checkIfBookmarked(final String title, callbackFunction){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference userBookmarks = FirebaseDatabase.getInstance().getReference().child("users")
.child(user.getUid()).child("bookmarks");
final boolean[] exists = new boolean[1];
userBookmarks.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
exists[0] = dataSnapshot.child(title).exists() ;
//execute your callback function here
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
return;
}

Check this to see how to pass a function as parameter.
Passing function as a parameter in java

An alternative would be to move your code into OnDataChange method

How do I get the value of this variable outside the .then((){}); statement in flutter?

If you use the .then() clause you need to do all your work inside it and you can't use its values outside because you don't know when you are receiving the answer.

You could await the answer there and mark the method that encloses your code with async.

bool check;
final docs = Firestore.instance.collection('tests').where('name',isEqualTo: snapshot['name'].replaceAll('.mp4','.txt')).getDocuments();
if(docs.documents[0].exists)
check = true;
else
check = false;
debugPrint(check.toString());

or

Future<void> doSomething() async {
bool check;
final docs = Firestore.instance.collection('tests').where('name',isEqualTo:
snapshot['name'].replaceAll('.mp4','.txt')).getDocuments();
if(docs.documents[0].exists)
check = true;
else
check = false;
debugPrint(check.toString());
}


Related Topics



Leave a reply



Submit