Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
How to export a global object in React js

I am trying to store the email of the user once successfully signed in.

For this,

  • Created a file logged_user.js
  • Created a class LoggedUser and a single instance of it named loggedUser.
  • Exported 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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda