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

275
Vistas
Why function from service class doesn't work from useContext?

I'm trying to pass service as context and then use it in app, but get error "service.getItems is not a function". What is wrong? I know I could just import and use it, but I'm trying to learn context thing. This works for normal functions, but not class.

import React, {useContext} from "react";
import { createRoot } from "react-dom/client";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

class Service {
  getItems() {
    return [1, 2, 3];
  }
}

const ServiceContext = React.createContext();

const App = () => {
  const service = useContext(ServiceContext)
  return <h1>{service.getItems()}</h1>; // service.getItems is not a function
};

root.render(
  <ServiceContext.Provider value={Service}>
    <App />
  </ServiceContext.Provider>
);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This error is not related to React or React Context, you need to declare a method as static if you want to call it like: ClassName.method

class Service {
  static getItems() {
    return [1, 2, 3];
  }
}

Service.getItems() //[1,2,3]

Or you can instantiate your class before passing it to the context:

root.render(
  <ServiceContext.Provider value={new Service()}>
    <App />
  </ServiceContext.Provider>
);

Now you can access the instance method as you were trying to do without it being static.

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