Search code examples
javascriptreactjsaxiosfetch

How to pass dynamic parameters to axios instance


I was just reading a css-tricks article on how to make you're API request DRY using axios HERE. Now reacting something like this would work fine :

export default axios.create({
  baseURL: 'https://mysite/v3',
  headers: {
    'content-type': 'application/json'
  }
})

The thing is what if i want to pass additional parameters to this instance ? I.E. i have another parameter that i would like to the header like so:

'X-USER-ACCESS-TOKEN': sessionToken,

Also what if i have multiple other options to pass to the header ?


Solution

  • To pass headers dynamically, you could export a function that takes options as an argument and returns a new instance of axios:

    // utils/custom-axios.js
    
    export default function(options = {}) {
      const { 
        headers = {} 
      } = options;
      
      return axios.create({
        baseURL: "https://mysite/v3",
        headers: {
          "Content-Type": "application/json",
          ...headers
        }
      });
    }
    

    Then you could use it the following way:

    const axios = require("./utils/custom-axios");
    
    const options = { 
      headers: { "X-USER-ACCESS-TOKEN": "secret" } 
    };
    
    axios(options)
      .post("./user.json", formData)
      .then(...)
      .catch(...);
    
    // alternatively, don't pass any options 
    axios()
      .post("./user.json", formData)
      .then(...)
      .catch(...);