0

I have a function:

const getCityId = (myCity) => {
        try {
            // set the url
            const myUrl = `https://................com/tabs/categories.json?orderBy="title"&equalTo="${myCity}"`;
            axios.get(myUrl).then((res) => {
                //console.log(res.data);
                const myData = res.data;
                for (var key1 in myData) {
                    for (var key2 in myData[key1]) {

                        var myCityId = myData[key1].id;
                    }
                }
                console.log('display....' + myCityId);
                return myCityId;
            });
        } catch (err) {
            console.log(err);
            return false;
        }
    };

Than in the code whenI do this:

newCityId = getCityId(newCity);

I get value 'Undefined'

If I try:

getCityId(newCity).then((response) => console.log(response));

I get error 'Cannot read property 'then' of undefined'

I am debugging function and I see in log that before return.. proper value is set...

I have no idea how it end up undefined on the end.

user13401262
  • 121
  • 10

1 Answers1

1

You are not returning anything from getCityId, hence the error of undefined

Change this :

axios.get(myUrl).then((res) => {

to :

return axios.get(myUrl).then((res) => { // <-- add return before axios

and then try this :

getCityId(newCity).then((response) => console.log(response));
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122