0

I've a .env file:

REACT_APP_API_KEY=1234567

Then I added that to my component:

const API_kEY = process.env.REACT_APP_API_KEY;
console.log("Key is", API_KEY);
const URL = "http://myapi.com?appid=${API_KEY}"  

I get API key in console successfully, but I get this error:

dashboard.js:26 GET http://myapi.com?appid=${API_KEY} 401 (Unauthorized)

How can I make URL to get the API KEY?

0

3 Answers 3

4

Problem is that you are using double quotes. Instead of using double quotes, you need to use a template literal.

With double quotes, your URL is literally

"http://myapi.com?appid=${API_KEY}"

but it should be

"http://myapi.com?appid=1234567"

Solution

Replace double quotes around the URL with backticks

const URL = `http://myapi.com?appid=${API_KEY}`

Alternatively, you could just concatenate the API key with the URL

const URL = "http://myapi.com?appid=" + API_KEY;
Sign up to request clarification or add additional context in comments.

Comments

0

You Need to use Template Literals (Backtick) here

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const API_kEY = process.env.REACT_APP_API_KEY;
console.log("Key is", API_KEY);
const URL = `http://myapi.com?appid=${API_KEY}`  

Comments

0

Example for weatherApp

.env

REACT_APP_KEY=04a1f006349043f7ae3145707222012
REACT_APP_URL= http://api.weatherapi.com/v1/current.json?aqi=no

Async Await Function:

async function loadInfo(city="london") {
    try {
        const request= await fetch(
            `${process.env.REACT_APP_URL}&key=${process.env.REACT_APP_KEY}&q=${city}`
        );
        const json = await request.json();
      console.log(json);
    } catch (error) {

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.