Search code examples
expoglobal-variables

how to call API_URL using global variable on Expo


I am trying to make call api using IP Address in Expo example like login function on react native

 UserLoginFunction = () =>
  { 
    const {UserEmail} = this.state;
    const {Password} = this.state;
    if (!UserEmail.trim()) {
      this.setState ({showError: this.state.UserEmail === ""})
      return;
    }
    if (!Password.trim()) {
      this.setState ({showError: this.state.Password === ""})
      return;
    }

    var api = "http://192.168.43.123/Api/login.php?email=" + UserEmail + "&password=" + Password;
    console.log(api);
    return fetch(api)
    .then((response) => response.json())
    .then((responseJson) => {
     /*console.log(responseJson.message);*/
      if(responseJson.status === true)
      {
        console.log(UserEmail);
        this.props.navigation.navigate('HomeScreen', { UserEmail : UserEmail });
      }
      else 
      {
        alert(responseJson.message)
      }
   
       }).catch((error) => {
         console.error(error);
       });
    
   }

I want to make global variable especially for IP Address like my PHP

public function linkUrl()
    {
        $value = "http://192.168.43.123/";

        return $value;
    }

Is it possible? I'm looking for this to make efficient so only 1 IP address can calling with declare API_URL or URL any suggest? thank you


Solution

  • You need to set BASE_URL manually.

    //config.js
    export const BASE_URL = "http://192.168.43.123";
    
    //in your js
    import * as config from 'config.js';
    ...
        fetch( config.BASE_URL+ '/path/to/your/api' )
    ...
    

    I also recommend you to use axios instead of fetch. Then you can set base_url globally