Dynamic Loading of Configuration with TanStack Config
Illustrate how to dynamically load different configurations at runtime using TanStack Config, enabling on-the-fly adjustments without application restart.
import { useConfig, ConfigProvider } from '@tanstack/config-react';
// Define a default configuration
const defaultConfig = {
apiBaseUrl: 'https://example.com/api',
featureFlag: false
};
This imports the necessary hooks and components from TanStack Config and defines a default configuration object. The defaultConfig object includes properties like the API base URL and a feature flag, which can be dynamically adjusted.
function App() {
const [config, setConfig] = React.useState(defaultConfig);
// Function to load configuration dynamically
const loadConfig = async () => {
// Simulate fetching new config from an API
const newConfig = await fetch('https://example.com/config').then(res => res.json());
setConfig(newConfig);
};
// Example of using the config
console.log(config.apiBaseUrl);
return (
<ConfigProvider config={config}>
{/* Your app components here */}
</ConfigProvider>
);
}
This component demonstrates setting up and using TanStack Config in a React application. It initializes state with the default configuration and defines a function to dynamically load a new configuration from an API. The loaded configuration updates the state, which is then provided to the application via ConfigProvider.
useEffect(() => {
loadConfig(); // Call loadConfig when the component mounts
}, []);
This useEffect hook calls the loadConfig function when the component mounts, ensuring that the application attempts to load and apply the new configuration immediately at startup.