Expose container via provider

This commit is contained in:
Alejandro Celaya
2025-11-15 10:20:53 +01:00
parent 6094994cfa
commit f301513f5b
15 changed files with 92 additions and 53 deletions

24
src/container/context.ts Normal file
View 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