Cannot set dynamic baseURL for axios in React Native

903 Views Asked by At

I am trying to set the axios baseURL based on a variable defined inside a separate file in React Native. However, this doesn't seem to work.

The URL is defined inside a constants file in the following way:

//constants.js

const constants = {};
constants.API_URL = "http://192.168.1.1:5002/api";

export default constants;

The variable is called inside an axios wrapper file in the following way:

//axiosWrapper.js
import axios from 'axios';
import constants from './constants'

axios.defaults.baseURL = constants.API_URL

The above throws the following error:enter image description here

However, if the variable is defined inside the axios wrapper file itself or if the URL is hardcoded, it works:

API_URL = "http://192.168.1.1:5002/api";
axios.defaults.baseURL = API_URL;

OR

axios.defaults.baseURL = "http://192.168.1.1:5002/api";

It would be great if someone could explain why this happens and if there's a way to fix it.

React Native version - 0.64.2
Axios version - 0.18.0
Platform - Android

1

There are 1 best solutions below

0
guiwme5 On

try this:

//constants.js

const API_URL = "http://192.168.1.1:5002/api";
const API_URL2 = "http://192.168.1.1:5002/api";

export { API_URL, API_URL2 };


//axiosWrapper.js
import axios from 'axios';
import * as constants from './constants'

axios.defaults.baseURL = constants.API_URL