Created
March 25, 2021 10:01
-
-
Save Drag13/06e450297cd0736e0059629660038abc to your computer and use it in GitHub Desktop.
Service locator injector example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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