Reputation: 181
i am getting base url from asyncstorage and i want to set it as base url for axios instance.
currently iam following below code but it is not working
const axiosInstance = axios.create({
// baseURL: API_END_POINTS.BASE_URL+AsyncStorage.getItem('dealerNo'),
});
axiosInstance.defaults.timeout = 10000000;
axiosInstance.interceptors.request.use(
async config => {
axiosInstance.defaults.baseURL=await getBaseUrl();
return config;
},
error => Promise.reject(error)
);
export async function getBaseUrl() {
var No = await AsyncStorage.getItem('dealerNo')
var value =API_END_POINTS.BASE_URL+ No;
return value;
}
axiosInstance.defaults.headers.post['Content-Type'] = 'application/json';
export default axiosInstance;
iam importing the above axiosInstance to make get or post calls.
Upvotes: 1
Views: 8155
Reputation: 2918
Make a function that returns the Axios instance with a dynamic base URL, like this:
custom-axios.js
import axios from 'axios';
const customAxios = (dynamicBaseURL) => {
// axios instance for making requests
const axiosInstance = axios.create({
baseURL: dynamicBaseURL
});
return axiosInstance;
};
export default customAxios;
and then use the instance as follows:
import axios from './custom-axios'
...
const axios1 = axios('/some-url');
const axios2 = axios('/another-url');
axios1.get('/base-is-some-url');
axios2.get('/base-is-another-url');
...
Upvotes: 3
Reputation: 2422
Instaed of axiosInstance.defaults.baseURL
, config.baseURL = await getBaseURL();
is enough and should work.
At least it sets baseURL corrrectly in my side.
Upvotes: 0