Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios conditional parameters

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=

like image 895
Alexander Kim Avatar asked Mar 04 '26 08:03

Alexander Kim


1 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 } : {})
  },
})
like image 197
Raghav Garg Avatar answered Mar 05 '26 22:03

Raghav Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!