hooks
useEnv

useEnv

A custom hook that manages environment variables.

Add hook

Create a file use-env.ts and copy & paste the code from useEnv.

Hook

⚠️
Make sure to have configuration file in your project .
 
import { NEXT_DEFAULT_ENV_VARS, VITE_DEFAULT_ENV_VARS, rehookConfig } from '../../rehook.config'
import { getEnv } from '../actions/env'
import { useEffect, useState } from 'react'
 
const { ignoreDefaultEnv, framework } = rehookConfig
 
const isFrameworkVite = framework === 'VITE' // Otherwise it is NEXTJS
 
export const useEnv = () => {
 
    const envVars = isFrameworkVite ? import.meta.env : process.env
 
    const [variables, setVariables] = useState(envVars)
 
    const ignoreDefaultVariables = () => {
        let ignoredVariables: { [key: string]: string }
 
        if (ignoreDefaultEnv) {
            ignoredVariables = {}
            for (const key in variables) {
                if (isFrameworkVite ? !VITE_DEFAULT_ENV_VARS.includes(key) : !NEXT_DEFAULT_ENV_VARS.includes(key)) {
                    ignoredVariables[key] = variables[key]
                }
            }
            setVariables(ignoredVariables)
        }
    }
 
    const addVariable = (variable: string, value: string) => {
        setVariables(prevVars => ({ ...prevVars, [variable]: value }))
    }
 
    const renameVariable = (oldVar: string, newVar: string) => {
        if (Object.prototype.hasOwnProperty.call(variables, oldVar)) {
            const updatedEnv = { ...variables }
            updatedEnv[newVar] = updatedEnv[oldVar]
            delete updatedEnv[oldVar]
            setVariables(updatedEnv)
        }
    }
 
    const updateVariable = (currentVarVar: string, newValue: string) => {
        if (Object.prototype.hasOwnProperty.call(variables, currentVarVar)) {
            setVariables(prevEnv => ({
                ...prevEnv,
                [currentVarVar]: newValue,
            }))
        }
    }
 
    const removeVariable = (currentVar: string) => {
        if (Object.prototype.hasOwnProperty.call(variables, currentVar)) {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { [currentVar]: _, ...updatedVariables } = variables
            setVariables(updatedVariables)
        }
    }
 
    const saveVariable = (variable: string, value: string) => {
        localStorage.setItem(variable, value)
    }
 
    const deleteVariable = (variable: string) => {
        if (localStorage.getItem(variable)) {
            localStorage.removeItem(variable)
        }
    }
 
    useEffect(() => {
        ignoreDefaultVariables()
    }, [])
 
    return { variables, addVariable, renameVariable, updateVariable, saveVariable, removeVariable, deleteVariable }
}
 
 

Usage

 
import { useState } from 'react'
import { useEnv } from './hooks/use-env'
 
function App() {
    const { variables, addVariable, updateVariable, saveVariable, removeVariable, deleteVariable } = useEnv()
 
    const [newVariable, setNewVariable] = useState('')
    const [newValue, setNewValue] = useState('')
 
    const handleAddVariable = () => {
        if (newVariable.trim() !== '' && newValue.trim() !== '') {
            addVariable(newVariable, newValue)
            saveVariable(newVariable, newValue)
            setNewVariable('')
            setNewValue('')
        }
    }
 
    const handleUpdateVariable = (variable: string, newValue: string) => {
        updateVariable(variable, newValue)
        saveVariable(variable, newValue)
    }
 
    return (
        <div className="App">
            <h1>Environment Variables</h1>
            <div>
                <input
                    type="text"
                    placeholder="Variable"
                    value={newVariable}
                    onChange={e => setNewVariable(e.target.value)}
                />
                <input type="text" placeholder="Value" value={newValue} onChange={e => setNewValue(e.target.value)} />
                <button onClick={handleAddVariable}>Add Variable</button>
            </div>
            <div>
                <h2>Existing Variables:</h2>
                <ul>
                    {Object.entries(variables).map(([variable, value]) => (
                        <li key={variable}>
                            {variable}: {value}{' '}
                            <button onClick={() => handleUpdateVariable(variable, prompt('Enter new value:'))}>
                                Update
                            </button>
                            <button onClick={() => removeVariable(variable)}>Remove</button>
                            <button onClick={() => deleteVariable(variable)}>Delete</button>
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    )
}
 
export default App
 
 
 

API

Returns

NameTypeDescription
variables{ [key: string]: string }An object containing the current environment variables.
addVariable(variable: string, value: string) => voidA function to add a new environment variable.
renameVariable(oldVar: string, newVar: string) => voidA function to rename an existing environment variable.
updateVariable(currentVar: string, newValue: string) => voidA function to update the value of an existing environment variable.
removeVariable(currentVar: string) => voidA function to remove an existing environment variable.
saveVariable(variable: string, value: string) => voidA function to save an environment variable to local storage.
deleteVariable(variable: string) => voidA function to delete an environment variable from local storage.

Contributors

Avatar 1