I’m trying to get a user’s IP address and show it in a table. I wrote a function to fetch the IP from an API, but it’s not working as expected. Here’s my code:
function fetchData(endpoint, handleResponse) {
const request = new XMLHttpRequest();
request.open('GET', endpoint);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
handleResponse(null, request.responseText);
} else {
handleResponse(new Error('Failed to fetch data'), null);
}
}
};
request.send();
}
let userIP = fetchData('api-endpoint-here', function(error, result) {
if (error) {
return error;
} else {
console.log('Result:', result);
return result;
}
});
console.log('User IP:', userIP);
When I run this, the console shows:
User IP: undefined
Result: 192.168.1.100
I’m confused why the IP is undefined outside the function but shows up inside. What’s going wrong here? How can I fix it so the IP is available outside the function?
hey, i see ur problem. fetchData is async, so userIP gets set before the callback runs. try using Promises or async/await instead. something like:
async function getIP() {
let ip = await fetch(‘api-endpoint-here’).then(res => res.text());
console.log(‘User IP:’, ip);
}
getIP();
this should work better for ya!
I’ve run into this exact problem before, mate. The issue is that JavaScript’s running your code asynchronously, so it’s not waiting for the API to respond before moving on. Here’s a quick fix that worked for me:
function getIP() {
return new Promise((resolve, reject) => {
fetchData('api-endpoint-here', (error, result) => {
if (error) reject(error);
else resolve(result);
});
});
}
getIP()
.then(ip => {
console.log('User IP:', ip);
// Update your table or do whatever with the IP here
})
.catch(error => console.error('Error fetching IP:', error));
This wraps your fetchData in a Promise, which lets you handle the result when it actually comes in. Give it a shot and let me know if you hit any snags!
The issue lies in the asynchronous nature of your fetchData function. It returns immediately, before the API call completes, hence the undefined value. To resolve this, you need to restructure your code to handle the asynchronous operation properly.
Consider using the Fetch API with Promises, which provides a cleaner syntax:
function getIP() {
return fetch('api-endpoint-here')
.then(response => response.text())
.catch(error => console.error('Error:', error));
}
getIP().then(ip => {
console.log('User IP:', ip);
// Use the IP here or update your table
});
This approach allows you to chain operations and handle the result when it’s available, ensuring you have the IP address before attempting to use it.