Axios conditional parameters

Viewed 15420
axios.get(globalConfig.FAKE_API, {
    params: {
        phone: this.phone,
        mail: this.mail
    },
})
.then((resp) => {
    this.req = resp.data
 })
.catch((err) => {
     console.log(err)
 })

Is there any way I can make conditional parameters when doing GET / POST requests with Axios? For example, if my mail parameter is empty, i won't send an empty parameter, like: someurl.com?phone=12312&mail=

2 Answers

Either you can maintain a variable of params before making a request and only add key if it has data like:

const params = {}
if (this.mail) { params.mail = this.mail }

or you can do like below, we write normal js code between ...() the parenthesis. We are adding a ternary condition.

axios.get(globalConfig.FAKE_API, {
  params: {
    phone: this.phone,
    ...(this.mail ? { mail: this.mail } : {})
  },
})

Reghav Garg's idea looks neat at first glance, but with more than one optional parameter, I'm afraid it will get messy.

You could simply use one of the common utility libraries like underscore or lodash and utilize their filter function:

const allParams = {
    mail: this.mail,
    phone: this.phone,
    // ...
};
axios.get(globalConfig.FAKE_API, {
   // 'Pick' takes only those elements from the object
   // for which the callback function returns true
   //
   // Double negation will convert any value to its boolean value,
   // so null becomes false etc.
   params: _.pick(allParams, (value, key) => { return !!value; })
})
Related