I know it is not possible to use Hooks in Class Components, that is not what I am trying to achieve.
I have a Context I want to access in a service class.
/* File MyComponent.tsx */
function MyComponent() {
MyService.foo();
return (
<h1>Anything</h1>
)
}
/* File MyService.tsx */
class MyService {
foo() {
const [dispatch] = React.useContext(MyContext);
dispatch({type: 'myaction'});
}
}
export default new MyService()
I Have already found a workaround by passing the dispatch callback from the component to the service method. But this is pretty ugly and tedious.
function useMyServiceFoo(params) {
const [dispatch] = React.useContext(MyContext);
MyService.foo(dispatch, params);
}
As this is working I wonder why it is not when I call useContext in the class methods ? Is there a way I can make it works ?