import { useState, useEffect, ReactNode, FC } from 'react'; import { Config, ConfigContext } from './ConfigContext'; export type ConfigLoaderFunction = () => Promise; export type ConfigProviderProps = { /** * Property that enables debugging from ConfigProvider for Async Loading */ debug?: boolean; /** * Property that represents the config object */ config?: Config; /** * Property that represents the React Children nodes */ children: ReactNode; /** * Property that represents a function that enables to resolve config loading in Async Way */ getConfig?: ConfigLoaderFunction; }; const log = (msg: string, debug?: boolean) => debug && console.warn(msg); export const ConfigProvider: FC = ({ debug, config, children, getConfig }: ConfigProviderProps) => { const [configuration, setConfiguration] = useState(config as Config); useEffect(() => { if (getConfig) { getConfig() .then((config: Config) => { log(`[ConfigProvider]: finish async loading with config: ${config}`, debug); setConfiguration(config); }) .catch((error: Error) => { log(`[ConfigProvider]: finish async loading with error: ${error}`, debug); setConfiguration(null); }); } }, [getConfig]); return {children}; }; ConfigProvider.displayName = 'ConfigProvider'; ConfigProvider.defaultProps = { debug: false };