2

I have a Mobile App that either uses a cloud server or a local server to serve information.

In my App.js I have:

helperUtil.apiURL().then((url) => { 
  global.API_URL = url;
})

The function does something like:

export async function apiURL() {

  try {
    var local = await AsyncStorage.getItem('local')
    local = (local === 'true')

    if(typeof local == 'undefined') return "https://api.website.com";
    else if(!local) return "http://192.168.0.6:8080";
    else return "https://api.website.com";
  }
  catch(err) {
    return "https://api.website.com";
  }

}

Then my fetch command would be:

fetch(global.API_URL+'/page', { 
  method: 'GET', 
  headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this.state.authtoken },
})

I'm running into problems here where the API_URL ends up undefined so I feel like there might be a better solution to this.

Open to any and all suggestions. Thank you.

1
  • I would look in to setting the URI in a environment variable somehow, that you then can load/import in code. Haven't done this before, but there seems to be a lot of suggestions on how to handle this: here and here for example. good luck Commented Jan 5, 2019 at 22:47

1 Answer 1

1

Insted of seetting url in global obj always use method which return a Promise, and it will return your global object if exist and if not get data from apiURL function. With async/await syntax fetch will be executed only when getAPI promise will be resolved and there will be no situation that url is empty.

const getAPI = () => {
    return new Promise((resolve, reject) =>{
         if(global.API_URL) {
              resolve(global.API_URL)
         } else {
              helperUtil.apiURL().then((url) => { 
                  global.API_URL = url;
                  resolve(url)
              })
         }

});


const fetchFunc = async () => {
   const url = await getAPI()

   fetch(url+'/page', { 
      method: 'GET', 
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer 
      '+this.state.authtoken },
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.