import React, { useEffect, useState } from "react"; import { ConfigContextProps, ConfigProviderProps } from "./types"; import { ConfigLocalType } from "./types"; import { ConfigContext } from "./context"; export const ConfigProvider: React.FC = (props) => { // Destructure props const { children, isAuth, configLocal, configService } = { ...props }; const [configs, setConfigs] = useState(null); const addConfig = (key: string, value: string) => { if (configs) setConfigs([...configs, { key, value }]); }; const getConfig = (key: any) => { if (configs != null) return configs[key]; else return ""; }; useEffect(() => { loadData(); }, [isAuth, configLocal, configService]); const loadData = async () => { if (isAuth) { try { if (configService) { const response = await configService(); if (response && response.error) { throw response.error; } setConfigs({ ...response.data, ...configLocal } as ConfigLocalType); } else { setConfigs({ ...configLocal } as ConfigLocalType); } } catch (error) { console.error('Error fetching configurations:', error); } } else { setConfigs(configLocal); } } const contextValue: ConfigContextProps = { configs: configs, addConfig, getConfig, }; return ( {children} ); }