Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created March 25, 2021 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drag13/06e450297cd0736e0059629660038abc to your computer and use it in GitHub Desktop.
Save Drag13/06e450297cd0736e0059629660038abc to your computer and use it in GitHub Desktop.
Service locator injector example
import { FC, createContext } from "react";
// Service locator:
interface IService {
test: () => string;
}
type ServiceLocator = {
myTestService: IService;
};
const serviceLocator: ServiceLocator = {
myTestService: { test: () => "hello world" },
};
// Context
const ctx = createContext(serviceLocator);
// HOC
const WithServiceLocator = <TProps extends {}>(
Child: React.ComponentType<TProps>
) => (props: Omit<TProps, keyof ServiceLocator>) => (
<>
<ctx.Consumer>
{(ctx) => <Child {...ctx} {...(props as TProps)} />}
</ctx.Consumer>
</>
);
// Component
type TestProps = {
myTestService: IService;
someData: string;
};
const MyComponent: FC<TestProps> = ({ myTestService }) => (
<>{myTestService.test()}</>
);
const ComponentWithService = WithServiceLocator(MyComponent);
// Application
const App: FC = () => (
<div>
<ComponentWithService someData="test data" />
</div>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment