Home > front end >  Why function from service class doesn't work from useContext?
Why function from service class doesn't work from useContext?

Time:05-15

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

CodePudding user response:

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.

  • Related