Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 21x 21x 184x 184x 126x 126x 126x 126x 184x 184x 21x 126x 126x 126x | import { createContext, ReactNode, useContext, useMemo } from "react";
import {
IComponentRepository,
RepositoryConfigs,
RepositoryDataTypes,
} from "./types";
import { createRepositoryHooks } from "./useWithRepository";
interface RepositoryContextValue<K extends string> {
getRepositoryHooks: <T>(
tag: K,
) => ReturnType<typeof createRepositoryHooks<T>>;
}
const RepositoryContext = createContext<RepositoryContextValue<any>>(
{} as RepositoryContextValue<any>,
);
interface Props<K extends string, T extends RepositoryDataTypes> {
children: ReactNode;
configs: RepositoryConfigs<K>;
repositories: {
[P in K]: IComponentRepository<T[P]>;
};
}
export const WithRepositoryProvider = <
K extends string,
T extends RepositoryDataTypes,
>({
children,
configs,
repositories,
}: Props<K, T>) => {
const contextValue = useMemo(() => {
const getRepositoryHooks = <D,>(tag: K) => {
const config = configs[tag];
const repository = repositories[tag];
Iif (!config || !repository) {
throw new Error(`No configuration or repository found for tag: ${tag}`);
}
return createRepositoryHooks<D>(config, repository);
};
return { getRepositoryHooks };
}, [configs, repositories]);
return (
<RepositoryContext.Provider value={contextValue}>
{children}
</RepositoryContext.Provider>
);
};
export const useRepository = <
K extends string,
T extends RepositoryDataTypes,
Tag extends keyof T,
>(
tag: Tag,
) => {
const context = useContext(RepositoryContext);
Iif (!context) {
throw new Error(
"useRepository must be used within the WithRepositoryProvider",
);
}
return context.getRepositoryHooks<T[Tag]>(tag);
};
|