Chris Garcia
Chris Garcia

Reputation: 15

API Key returning undefined react

I am working to build a weather app in react, and I need to use 2 api keys. I have a .env setup and it is working fine for the first key, but I cannot seem to get my second key to return a value, it keeps showing as undefined when I make my fetch call.

My .env is setup as below. I know that the naming convention needs to include REACT_APP to be picked up but I am unsure of how to differentiate the two of them and have them still be picked up.

REACT_APP_APIKEY={MyOpenWeatherAPIKEY}
REACT_APP_APIKEY2={MyUnSplashAPIKEY} 

Any idea of how to resolve?

EDIT: For anyone having the same issue. the answer is the right way to have the keys setup in the .env file. but do not forget to kill your app and then restart it after making changes to the .env file.

Upvotes: 1

Views: 960

Answers (2)

Ahmed Hosny
Ahmed Hosny

Reputation: 480

try this inside your .env :-

REACT_APP_OPEN_WEATHER_KEY=whateveryouropenweatherkeyis
REACT_APP_UNSPLASH_KEY=whateveryourunsplashkeyis

note that curly braces are not required here

then you can access them anywhere in your code like this : process.env.REACT_APP_OPEN_WEATHER_KEY , process.env.REACT_APP_UNSPLASH_KEY

NB : make sure .env is in the root project directory i.e. same with package.json

Upvotes: 1

mmantach
mmantach

Reputation: 148

no need to add to the variable REACY_APP you can define the variable name in the env file

OPEN_WEATHER={APIKEY}

first you need to install dotenv package npm install dotenv --save

add this line to your app :

require('dotenv').config()

and finaly use this command to get the variable value

process.env.OPEN_WEATHER

let me know if you need any other help

Upvotes: 0

Related Questions