Skip to content

Instantly share code, notes, and snippets.

@pwelter34
Created March 31, 2020 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwelter34/0876406691d2316c07ba5c12ea6b4517 to your computer and use it in GitHub Desktop.
Save pwelter34/0876406691d2316c07ba5c12ea6b4517 to your computer and use it in GitHub Desktop.
React Configuration Loader
import React, { useState, useEffect, createContext } from "react";
import Loader from './Loader';
interface Props {
children: JSX.Element;
file?: string;
}
interface IConfiguration{
version?: string,
clientDomain?: string,
serviceDomain?: string,
serviceEndpoint?: string,
clientId?: string,
tenantId?: string,
cacheLocation?: string,
}
export const ConfigurationContext = createContext<IConfiguration>({});
const ConfigurationLoader = (props: Props) => {
const [configuration, setConfiguration] = useState<IConfiguration>({});
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const path = props.file ?? '/config.json';
useEffect(() => {
setBusy(true);
fetch(path)
.then(response => response.json())
.then(data => setConfiguration(data))
.catch(error => setError(error))
.finally(() => setBusy(false));
}, [path])
return (
<ConfigurationContext.Provider value={configuration}>
{error && <div>Something went wrong ...</div>}
{busy ? <Loader /> : props.children}
</ConfigurationContext.Provider>
)
}
export default ConfigurationLoader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment