Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!