Created
March 31, 2020 17:29
-
-
Save pwelter34/0876406691d2316c07ba5c12ea6b4517 to your computer and use it in GitHub Desktop.
React Configuration Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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