Jesus
Jesus

Reputation: 485

Create dynamic axios client

I have a base axios client as:

import axios from "axios";

const httpClient = axios.create({
  baseURL: "https://localhost:7254/test",
});

httpClient.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
);

httpClient.interceptors.response.use(
  (response) => response,
  (error) => Promise.reject(error)
);

export default httpClient;

Then I use in my service as:

export const myService = createService(base);

This works as expected, but now I want to do the client dynamic to accept whatever controller, actually it has a static: /test "https://localhost:7254/test"

But I want to change it in oreder to do something like this on my services

 export const myService = createService(`{base}/test`);
 

How can I achieve that? Regards

Upvotes: 1

Views: 283

Answers (1)

captainskippah
captainskippah

Reputation: 1559

If your createService currently accepts an instance of axios and you want to replace the baseURL inside the createService, then just do

function createService(axiosInstance) {
  axiosInstance.defaults.baseURL = 'something/else/here'
}

Docs: https://axios-http.com/docs/config_defaults


The OP lacks a bit of context because there are some cases this is valid, but IMO, you seem to be doing the right thing.

Instead of replacing the baseURL somewhere, just set the proper value from the first place. Something like:

const httpClient = axios.create({
  baseURL: process.env.BASE_URL,
});

createService(httpClient)

Upvotes: 1

Related Questions