Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Cómo exportar un objeto global en React js

Estoy tratando de almacenar el correo electrónico del usuario una vez que haya iniciado sesión correctamente.

Para esto,

  • Creó un archivo logged_user.js
  • Creó una clase LoggedUser y una única instancia de la misma denominada loggedUser .
  • loggedUser exportado.

Supuse que donde sea que vaya a importar logged_user.js , solo obtendré esa única instancia. Pero en realidad, estoy recibiendo una nueva instancia.

<usuario_registrado.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;

Función de manejo de inicio de sesión

 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 }); } }

Una vez que el usuario inició sesión, la ruta cambia de la página de inicio de sesión a la página de administración. Allí estoy tratando de obtener acceso a ese correo electrónico, pero resulta ser null .

 async componentDidMount(){ const collegeName = await await getCollegeName(loggedUser.email); this.setState({collegeName: collegeName}) }

Quiero que solo se importe una sola instancia de LoggedUser en todos los archivos.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

loggedUser en realidad se exportó una vez. Según el estándar ECMA 2015, la export es una operación idempotente. El problema real aquí es la pérdida de this . La forma más sencilla de arreglarlo es usar funciones de flecha para métodos de clase:

 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;

Este es un mecanismo JS genérico que no tiene nada que ver con React

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!