1

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.

bryan
  • 8,879
  • 18
  • 83
  • 166
  • 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](https://medium.com/differential/managing-configuration-in-react-native-cd2dfb5e6f7b) and [here](https://stackoverflow.com/questions/33117227/setting-environment-variable-in-react-native) for example. good luck – micnil Jan 05 '19 at 22:47

1 Answers1

0

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 },
    })
}
Łukasz Blaszyński
  • 1,536
  • 1
  • 8
  • 13