0

I am using Geoapify to get customer location by IP, I want to change "href" after that depending on the location. This is what I am doing to get the location

var requestOptions = {   method: 'GET', };

var obj;

fetch("https://api.geoapify.com/v1/ipinfo?&apiKey=API_KEY", requestOptions)
.then(response => response.json())
.then(result => obj = result)
.then(() => console.log(obj))
.catch(error => console.log('error', error));

after that, I want to do something like that to change the href inside a tag

if (obj.country.name="United Arab Emirates"){
    var strLink = "URL";
    document.getElementById("cam-link").setAttribute("href",strLink);
    } else if (obj.country.name="Saudi Arabia"){
    var strLink = "URL";
    document.getElementById("cam-link").setAttribute("href",strLink);
    }else{
    var strLink = "URL";
    document.getElementById("cam-link").setAttribute("href",strLink);
    }

but javascript always execute the if condition before fetching the response, so it doesn't work, can someone help me with that please?

Mohab Mostafa
  • 109
  • 1
  • 8
  • 2
    put your code in the `.then(result => obj = result)` instead of `obj = result` just put the code in there - because that's how asynchrony works – Bravo Aug 23 '21 at 06:38
  • 1
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Aug 23 '21 at 06:39
  • @Bravo if condition doesn't work inside that, or maybe you can guide me more on that, I tried fetch("https://api.geoapify.com/v1/ipinfo?&apiKey=API_KEY", requestOptions) .then(response => response.json()) .then(if(result.country.name="Egypt"){console.log("Hello");}else{console.log("world");}) .catch(error => console.log('error', error)); – Mohab Mostafa Aug 23 '21 at 07:15
  • @SebastianSimon unfortunately no – Mohab Mostafa Aug 23 '21 at 07:15
  • 1
    `.then` requires the arguments to be a **function** ... not inline code like you have – Bravo Aug 23 '21 at 07:19

0 Answers0