-1

This is my first react app and I am trying to fetch API using axios.

The URL can be changed based on a value.

My code is

fetchURL(page,checked) {
  if(checked)
  {
     const apiUrl = 'firstApiURL'
  }
  else {
     const apiUrl = 'secondApiURL';
  }
   axios.get(apiUrl)......
}

It says apiUrl is undefined.

I thought it would be easy to change the API url based on another variable.

Any help is highly appreciated.

Prithviraj Mitra
  • 11,002
  • 13
  • 58
  • 99

3 Answers3

4

Constants are scoped to the block they are declared in (between the { and the } associated with the if and the else respectively and are not accessible outside that scope.

Define a variable outside the block and use that instead.

fetchURL(page,checked) {
  let apiUrl;
  if(checked)
  {
    apiUrl = 'firstApiURL'
  }
  else {
    apiUrl = 'secondApiURL';
  }
   axios.get(apiUrl)......
}

You can then use a default value instead of an else.

fetchURL(page,checked) {
  let apiUrl = 'secondApiURL';
  if(checked)
  {
    apiUrl = 'firstApiURL'
  }
  axios.get(apiUrl)......
}

Or to simplify further and still use const

fetchURL(page, checked) {
  const apiUrl = checked ? 'firstApiURL' : 'secondApiURL';
  axios.get(apiUrl);
}
Josh G
  • 644
  • 7
  • 21
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

In your code the const are defined in the block scope of {} so they are undefined outside.

Use let so you can assign to it, and declare it outside the if/else

let apiUrl;
if (checked) {
  apiUrl = 'firstApiURL'
} else {
  apiUrl = 'secondApiURL';
}
axios.get(apiUrl)......
}

for more info on block statements and scope read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/statements/block

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

const key word create constant which exists only in blocks in which they were created (let and const words create block-scope variables).

if() { } and else { } are blocks for our created apiUrl, and ``apiUrl do not exist outside them.

You could write let variable outside if and else and then write to it some value. For example:

fetchURL(page,checked) {
  let apiUrl;
  if(checked)
  {
     apiUrl = 'firstApiURL'
  }
  else {
     apiUrl = 'secondApiURL';
  }
   axios.get(apiUrl)......
}
Fiszcz
  • 101
  • 1
  • 8