Reputation:
I'm saving the user object in localstorage upon creation (to be sure i can use it later inside a custom function, outside the authStateChanged):
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.then(e => {
var user = firebase.auth().currentUser;
localStorage.setItem('fireUser', JSON.stringify(user));
user.sendEmailVerification();
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
});
then i'm retrieving it inside my custom function below, it works when used like user.uid
but it gives error "user.delete is not a function" when used as user.delete()
, why is that? the variable user
looks like this in the localStorage:
my custom function:
var myTimer;
function validTimer(timerValid){
var user = JSON.parse(localStorage.getItem('fireUser'));
// var buser = firebase.auth().currentUser; <-- doesn't work here
myTimer = setInterval(function() {
timerValid++;
localStorage.setItem('fireTimer', timerValid);
if (timerValid == 22) {
// delete in database
var userId = user.uid;
var ref = firebase.database().ref().child('users');
ref.child(userId).once("value", function(snapshot){
if (snapshot.exists()){
database.ref("users/"+userId).remove();
}
});
// delete account
user.delete().then(function() { // this says user.delete is not a function
}).catch(function(error) {
});
}
}, 1000);
}
Upvotes: 3
Views: 2363
Reputation: 1651
It’s stripped of its instance methods when you stringify and parse it back. The delete method is an instance method for a firebase user object. In this case your user, although it looks the same, is not a firebase user. It’s just a bare object.
For persisting the firebase user via the Client SDK, you want to use the firebase.auth().onAuthStateChanged()
method. Shortly after your page reloads, this method will fire. Set it here. Straight from the web starting guide:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
Upvotes: 2