Assign getJSON() query result to variable

Hello everyone,

I need your help with a simple function that logs users’ IP addresses based on a client-side JSON request. Here is my code:

import {getJSON} from "wix-fetch";

let userIp;

$w.onReady(function () {
    getUserIp();
    console.log(userIp);
});

export function getUserIp(){
    getJSON("API Endpoint")
    .then(json => {
        userIp = json.query;
    })
}

My main function is getUserIp(), which attempt to assign “json.query” to the userIp global variable. However, my console returns “undefined” when trying to access the variable.

Please let me know how to solve this issue. Any help is much appreciated!

Hi :wink:

Using fetch to get a JSON or a response always resolve to a Promise , which will take some time to get the answer from the 3rd party server, and you’re printing the IP immediately before the previous promise is resolved, that’s why you’re getting an undefined value.

To fix this, you need to make use of async/await to wait until the promise is resolved (the IP is fetched), then print the value of the IP.

You can do it by changing the page’s onReady( ) function into an async one.

$w.onReady(async function () {
    await getUserIp();
    console.log(userIp);
});

Or by changing your function “getUserIp” to return a Promise.

import {getJSON} from "wix-fetch";

let userIp;

$w.onReady(function () {
    userIp = await getUserIp();
    console.log(userIp);
});

export function getUserIp(){
    return getJSON("API Endpoint").then(json => {
       return Promise.resolve(json.query);
    }).catch(err => {
        console.error(err);
        return Promise.reject("Fetching the IP address has failed!");
    })
}

Hope this helps~!
Ahmad

As Ahmad said, you need to handle the returned Promise.

Another approach (not using a global variable for the returned IP):

import { getJSON } from "wix-fetch";

$w.onReady(function () {
    getUserIp().then((ip) => {
        console.log(ip);
    });
});

export function getUserIp() {
   return getJSON("https://extreme-ip-lookup.com/json")
        .then(json => {
           return json.query;
        })
}