Reputation: 59
I'm trying to get the uID ( User ID ) from my auth component in the app.component.ts file but it's giving me an 'Object is possibly null' error.
The function updates/creates a firestore document with the username & bio. It gets called only once the user enters the necessary details, but seems like Angular does not know that and thinks that the part of the code that gets the uID is going to be null, and I'm not sure how to go about it. The error underlines the
this.firebasetsAuth.getAuth().currentUser
part of the code. Here's the faulty code.
app.component.ts faulty code snippet
onSaveChangesClick(
usernameInput: HTMLInputElement,
bioInput: HTMLTextAreaElement
) {
let username = usernameInput.value;
let bio = bioInput.value;
this.firebasetsFirestore.create(
{
path: ["Users", this.firebasetsAuth.getAuth().currentUser.uid],
data: {
username: username,
bio: bio
},
onComplete: (docId) => {
alert("Profile Updated!");
},
onFail: (err) => {
}
}
);
}
Upvotes: 2
Views: 342
Reputation: 1000
This is a feature of strict typing in Typescript. The currentUser object could be null if no user is signed in. The TS linter has no way of knowing that when this chunk of code gets executed you will have an authenticated user.
You can fix this by ensuring that the user is not null by doing a quick check
if (isNotNullOrUndefined(this.firebasetsAuth.getAuth().currentUser)) {
// put code here
}
Or by using the optional chaining (?.
) operator
this.firebasetsAuth.getAuth().currentUser?.uid
Upvotes: 3