mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2026-07-24 04:31:52 +00:00
Expose container via provider
This commit is contained in:
24
src/container/context.ts
Normal file
24
src/container/context.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { IContainer } from 'bottlejs';
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
const ContainerContext = createContext<IContainer | null>(null);
|
||||
|
||||
export const ContainerProvider = ContainerContext.Provider;
|
||||
|
||||
export const useDependencies = <T extends unknown[]>(...names: string[]): T => {
|
||||
const container = useContext(ContainerContext);
|
||||
if (!container) {
|
||||
throw new Error('You cannot use "useDependency" outside of a ContainerProvider');
|
||||
}
|
||||
|
||||
return names.map((name) => {
|
||||
const dependency = container[name];
|
||||
if (!dependency) {
|
||||
throw new Error(`Dependency with name "${name}" not found in container`);
|
||||
}
|
||||
|
||||
return dependency;
|
||||
}) as T;
|
||||
};
|
||||
|
||||
// TODO Create Higher Order Component that can pull dependencies from the container
|
||||
Reference in New Issue
Block a user