I'm rebuilding my Expo app in pure React Native and trying to figure out the environment variable situation. I'm trying out react-native-config, currently on "^1.5.1". I installed using yarn add react-native-config
and then I did npx pod-install
.
Here is my .env file:
ENV_NAME=prod
TEST_ENV_VAR=hello
And for one of my components, I have code like this:
import Config from "react-native-config";
export function LoginScreen({ navigation }) {
...
const [isDev, setIsDev] = React.useState(Config.ENV_NAME === 'dev')
const [testEnvString, setTestEnvString] = useState(Config.TEST_ENV_VAR)
...
return (
...
{isDev ?
<View style={styles.row}>
<Text>Debug info: {isDev}</Text>
<Text>Test string: {testEnvString}</Text>
</View>
: null}
...
)
What I'm finding is that:
isDev
always evaluates to true, ie that snippet in the return ( ) is always showing, even when the .env file has ENV_NAME=prodisDev
does not itself show up as a value after the string "Debug info: " - so it's some kind of value that shows up as blank but evaluates to truetestEnvString
also does not show up in the displayed component
Am I missing anything in my setup here?
Addendum: I'm testing on iOS simulator (I don't care about Android yet) with npm start
Try cleaning your iOS build and then rebuilding. From my experience,
.env
or change to.env
is not loaded until the project is completely rebuilt from scratch.react-native-clean-project is a handy tool to perform the cleaning task. Follow the instruction to install, run
npm run clean
, and answer yes only to "Wipe iOS build folder". Once the cleaning is done, rebuild the app and you shall see the values.env
.One caveat of using react-native-clean-project is that it favors interactive prompt. There are non-interactive flags, but they are quite lacking. Thus, if you want to do the cleaning non-interactively, run the following command (copied from here):