Reputation:
Guys need your help.
I want to store variable in .env
file and use it in componentDidMount
. However, when I try and output it using console.log()
, it is undefined
.
I added a .env
file in root directory.
REACT_APP_GITHUB_CLIENT_ID ='8eb5e613906409cd0202'
REACT_APP_GITHUB_CLIENT_SECRET ='6b06c1e6f682c2de048c47958f6af15911251d25'
In the console.log()
function, both Id
and secret
are undefined
.
[edit: Here is the code]
componentDidMount() {
console.log(process.env.REACT_APP_GITHUB_CLIENT_ID)
this.setState({ loading: true })
axios.get(https://api.github.com/users?client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET})
.then(res => this.setState({ users: res.data, loading: false }))
.catch(err => console.log(err))
}
Upvotes: 0
Views: 354
Reputation: 141
You can use the dotenv
library to manually load environment variables (since react fails to do so).
Install it using
npm i dotenv
In development, use it in the following manner:
// index.js
import React from 'react'
import dotenv from 'dotenv'
dotenv.config({ path: '/custom/path/to/.env' }) // path optional argument
// ...
Checkout more from npmjs.com here
Upvotes: 0
Reputation: 13
your .env
file is not created properly and it is outside src
move it to src
folder
Upvotes: 1