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

109
Visualizações
React useContext method scope

I create custom hooks for reading state stores in my applications. const store = useStore(); Which I define as:

const store = new Store();

const StoreContext = createContext(store);
StoreContext.displayName = "StoreContext";

function useStore(): Store {
  const context = useContext(StoreContext);
  if (!context) {
    throw new Error("useStore must be used within MyProvider");
  }
  return context;
}

export { store, useStore };

Store itself is almost always a class with multiple fields and methods. Let's say I define it with example methods:

export class Store {
  /** Here is some other code with constructor, methods, fields etc... */
  public doSomething() { return this.doSomthingElse() };
  private doSemothingElse() { console.log("done something else")};
}

Why is it that when I use my hook like this with destructuring: const { doSomething } = useStore(); I get can not read property doSomethingElse of undefined meaning this is undefined, that way. But when I do: const store = useStore(); store.doSomething(); It works just fine?

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

0

It works that way due to this behaviour in JS classes. Binding calling method to this inside a constructor solves the issue with undefined context within a hook.

this.doSomething = this.doSomething.bind(this);

Kudos to Gabriele Petrioli for giving explanation.

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