I am trying to store the email of the user once successfully signed in.
For this,
logged_user.js
LoggedUser
and a single instance of it named loggedUser
.loggedUser
.I was assuming that where ever I am going to import logged_user.js
, I am going to get that single instance only. But actually, I am getting a new instance.
<logged_user.js>
class LoggedUser{
#email;
#userExist;
constructor(){
this.#email = null;
this.#userExist = false;
}
setUser(email){
this.#email = email;
this.#userExist = true;
}
resetUser(){
this.#email = null;
this.#userExist = true;
}
get userExist(){
return this.#userExist;
}
get email(){
return this.#email;
}
}
const loggedUser = new LoggedUser();
export default loggedUser;
Function handling signing in
async handleSingIn() {
this.clearAlert();
this.setState({ loading: true });
if (this.validateEmailAndPassword()) {
await signIn(this.state.emailInput, this.state.passwordInput)
.then(() => {
this.setState({ loading: false });
this.showAlert("Signed In.", false);
loggedUser.setUser(this.state.emailInput);
window.location.href = "/adminPanel";
})
.catch((error) => {
this.setState({ loading: false });
switch (error.code) {
case "auth/invalid-email":
this.showAlert("Invalid email!");
break;
case "auth/wrong-password":
this.showAlert("Wrong password!");
break;
case "auth/user-not-found":
this.showAlert("User not found!");
break;
default:
alert(error.message);
this.showAlert("Something went wrong!");
}
});
} else {
this.setState({ loading: false });
}
}
Once the user signed in the route is switched from Login page to admin page. There I am trying to get access to that email but it comes out to be null
.
async componentDidMount(){
const collegeName = await
await getCollegeName(loggedUser.email);
this.setState({collegeName: collegeName})
}
I want only a single instance of LoggedUser
to be imported throughout all the files.
loggedUser
actually exported once. As per ECMA 2015 standard export
is an idempotent operation. The real issue here is the lost of this
. The simplest way to fix it it to use arrow functions for class methods:
class LoggedUser{
#email;
#userExist;
constructor(){
this.#email = null;
this.#userExist = false;
}
setUser = (email) => {
this.#email = email;
this.#userExist = true;
}
resetUser = () => {
this.#email = null;
this.#userExist = true;
}
get userExist(){
return this.#userExist;
}
get email(){
return this.#email;
}
}
const loggedUser = new LoggedUser();
export default loggedUser;
This is a generic JS mechanism that has nothing to do with React