There are many solutions here and elsewhere, but it seems like the simple question of actually saving a piece of fetched text or json data to a variable for later use is rarely addressed. I have this:
let ip;
const URL = 'https://api.ipify.org'
const userIp = ((url) => {
fetch(url)
.then(res => res.text())
.then(data => ip = data)
.then(() => console.log(ip)) // Logs the IP
})
// I want to use "ip" as a variable in the rest of my code
(console.log(ip) // naturally returns undefined
console.log(userIp(URL)) // Variations of this gives me the promise
I have also tried variations of the following:
const URL = 'https://api.ipify.org'
let userIp;
const getIp = (url) => {
return fetch (url)
.then( response => response.text())
.then( result => result)
}
let ip = getIp(URL)
.then(result => {
userIp = result
})
console.log(ip) // Promise <pending>
Have also tried async/await with the same result, the IP address logs fine inside of the function but "impossible" [EDIT: maybe my quotation marks are redundant, commenters say it's impossible to do what I wanted to do] to make use of it outside of the scope.
I have also tried to call the function where the variable will be used from inside the then(), with the variable as a parameter. But couldn't get that to work either (and besides, the variable isn't ready to be used immediately, it should be triggered by a click event).
So the question is: How should I best get an IP variable that holds my IP string to be of use by other functions further down the script?