Created
March 8, 2024 17:27
-
-
Save jbmusso/8c54d0a757311fd5f0c00a11f402a96e to your computer and use it in GitHub Desktop.
React service injector
This file contains hidden or 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 * as React from "react" | |
const createServicesContext = < | |
Services extends Record<string, any> | |
>(): React.Context<Services> => { | |
return React.createContext<Services>({} as Services) | |
} | |
type ServicesInjector<S extends Record<string, any>> = { | |
ServicesProvider: ({ | |
children, | |
services | |
}: React.PropsWithChildren<{ services: S }>) => JSX.Element | |
useService: <ServiceName extends keyof S>( | |
serviceName: ServiceName | |
) => S[ServiceName] | |
} | |
export const makeServicesInjector = < | |
S extends Record<string, any> | |
>(): ServicesInjector<S> => { | |
const ServiceContext = createServicesContext<S>() | |
const useService = <ServiceName extends keyof S>( | |
serviceName: ServiceName | |
): S[ServiceName] => { | |
return React.useContext(ServiceContext)[serviceName] | |
} | |
const ServicesProvider = ({ | |
children, | |
services | |
}: React.PropsWithChildren<{ services: S }>): JSX.Element => { | |
return ( | |
<ServiceContext.Provider value={services}> | |
{children} | |
</ServiceContext.Provider> | |
) | |
} | |
return { | |
ServicesProvider, | |
useService | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment