Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda