What would be the best way to have fallback values in react, so for example if the .env variable is not available or the windows variable, could I make it fallback to the default URL?
for example:
const url = `${process.env.REACT_APP_URL}` ?? `${window._env_.REACT_APP_URL}` ?? 'https://xxxxx';
So for example if none of the first two are available then it will use the last hardcoded URL?
Is that correct or is there a better way to do it?
CodePudding user response:
I think a good way is to create a config file and put your default values in it.
Config.js
export const Config = {
REACT_APP_URL: 'something
}
And take the same values from it if they don't exist in env.
Usage:
const url = process.env.REACT_APP_URL || Config.REACT_APP_URL
CodePudding user response:
If you get rid of the ${}
it should work:
const url = process.env.REACT_APP_URL ?? window._env_.REACT_APP_URL ?? 'https://xxxxx';
CodePudding user response:
I'd propose you have a config file and import it whenever you want to use variables in it. I'm not sure it's the best solution but it's following Single Source of Truth principle and you can have all fallback values in there. For example
export default AppConfigs = {
REACT_APP_URL: process.env.REACT_APP_URL || window._env_.REACT_APP_URL || 'https://xxxxx';
}
And in other files, you just simply import it
import AppConfigs from './AppConfigs'
const url = AppConfigs.REACT_APP_URL
CommonJS
const AppConfigs = require('./AppConfigs')
const url = AppConfigs.REACT_APP_URL
In this way, you can control all your configs in one place and help you manage your configs easier. Beyond that, it's really useful in unit tests' implementation, once you only need to mock all configs in a single file.
ESLint also suggests that we should not use process.env
directly here