If this is just adding BASE_URL
, then this can be achieved by declaring it inside a constants.js
file and exporting it from there. But then, that makes us do BASE_URL + "something"
each time we make a network request which isn't really ideal either. Also there might be some scenarios where other configuration have to be shared, like say, a common header that has to be added to all the requests.
To solve this, most request libraries have in-build solutions. If we are choosing axios as the most popular one, we can create a instance like:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
export default instance;
and import this everywhere the axios
is going to be used like:
import axios from "./axios-instance";
assuming axios-instance.js
is the file where the instance is created. Now you can skip adding the BASE_URL
to every request as it is already provided in the instance.