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

277
Visualizações
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 Respostas
Responde à pergunta

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 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