-1

I would like to use the returned IP-adress in my normal JavsScript code outside of fetch function. Everything works fine when I print out the IP-adress inside the fetch funtion. But as soon as I try to log "ip" outside of it, it returns "undefined". I know this may be because fetch is asynchronus, but I do not know how to solve this problem. I would really appreciate some help!

 
function getIP(){
  let ip;
  fetch('https://api.ipify.org/?format=json')
    .then(result => result.json())
    .then(data => {
      ip = data.ip;
      console.log(ip);
    });
  console.log(ip);
}
      
leonski1
  • 1
  • 1
  • 1

1 Answers1

1

It’s because fetch is asynchronous.

const getIP = async () => {
    let ip;
    await fetch('https://api.ipify.org/?format=json')
    .then(result => result.json())
    .then(data => {
        ip = data.ip;
        console.log('test',ip);
    });
    console.log('test2',ip);
};

getIP();

Your function must be asynchronous as well and tell inside to wait fetch to be completed.

MickGe
  • 111
  • 2
  • 5
  • Thanks very much for your reply. As soon as I use getIP() in another function, the same problem occurs again. I need the IP as a String, I dont think this is the case now... – leonski1 Jul 17 '21 at 18:34
  • @leonski1 you’re welcome. It should be a string, but to be sure you can use `.toString()`. And you can use return in the function if you need to use it again. – MickGe Jul 17 '21 at 18:38