bable.config.js File
plugins: [
["module:react-native-dotenv", {
"envName": "APP_ENV",
"moduleName": "@env",
"path": ".env",
"blocklist": null,
"allowlist": null,
"blacklist": null, // DEPRECATED
"whitelist": null, // DEPRECATED
"safe": false,
"allowUndefined": true,
"verbose": false
}]
]
.env File code
API_LOGIN=https://example.in/login
login.js
import { API_LOGIN } from '@env';
const url = API_LOGIN;
let email = this.state.gmail;
let password = this.state.password;
fetch(url, {
method: 'POST',
body: JSON.stringify({
email: email,
password: password,
}),
headers: new Headers({
'Content-Type': 'application/json',
}),
})
.then((res) => res.json())
.catch((error) => console.error('Error : ', error))
.then((response) => {
if (response.access_token != undefined) {
this.setState({
accessToken: response.access_token,
});
if (this.state.accessToken != '') {
this.props.navigation.navigate('VolunteerHome', {
AccessToken: this.state.accessToken,
});
}
} else {
alert('Unauthorised User');
}
});
In the above code, I have installed dotenv. Then I have added the plugin code in the bable.config.js file. then I have create .env file in root directory and created the environmental variable API_Login=example.in/login then import the package in login.js file and use that variable. But I got a network error in my code if I simply add the API URL in the login file then my code run properly. please help me to solve this problem
If you try to use it as a string ?
const url = `${API_LOGIN}`;
You can also import it like that : process.env.API_LOGIN
You also need require('dotenv').config()
More info here