Created
July 6, 2022 19:45
-
-
Save Hawaii66/9ab37f3f71376054a1ac571cdf14476f to your computer and use it in GitHub Desktop.
useEnv() | Custom Hook | React
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 { useEffect, useState } from "react"; | |
export enum EnvVariable { | |
enviorment, | |
serverEndPoint, | |
website | |
} | |
type EnvVariables = {[key in keyof typeof EnvVariable]:string} | |
const DefaultVariables:EnvVariables = { | |
enviorment:"local", | |
serverEndPoint:"http://localhost:5000", | |
website:"http://localhost:3000" | |
}; | |
export function useEnvKey(key:EnvVariable, defaultValue:string) | |
{ | |
const enviormentVaribles = useEnv(); | |
var variable = enviormentVaribles[key]; | |
if(variable === "") variable = defaultValue; | |
return variable; | |
} | |
export function useEnv() | |
{ | |
const [variables, setVariables] = useState(DefaultVariables); | |
const getVariables = () => { | |
var variables:EnvVariables = DefaultVariables; | |
for(var enviormentVariable in EnvVariable) | |
{ | |
var value = process.env["REACT_APP_" + enviormentVariable]; | |
if(value === undefined) value = ""; | |
variables[enviormentVariable] = value; | |
} | |
setVariables(variables); | |
} | |
useEffect(()=>{ | |
getVariables(); | |
},[]) | |
return variables | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment