Shruti sharma
Shruti sharma

Reputation: 211

Making request parameter optional in axios get request

I have below axios request.

import axios from 'axios';
axios.get('/user', {
    params: {
      ID
      Name
    }
  })
  .then(function (response) {
    console.log(response);
  })

I want all the request parameter should be optional. if user send ID then it should give ID, if user enter ID and Name it should consider both. If user enters none it should display all the record.

I dont know how to handle this in react.

Upvotes: 2

Views: 4118

Answers (2)

arbitrary_A
arbitrary_A

Reputation: 373

think u are looking for something like below:

params: {
   ...(ID && {
      ID: ID
    }) // conditional spread operator
}

Upvotes: 4

Sid Barrack
Sid Barrack

Reputation: 1231

You would evaluate the params in a variable based on a condition before giving them to axios:

const parameters = condition ? {ID: id, Name: name} : {};
axios.get('/user', {
params: parameters
})
.then(function (response) {
console.log(response);
})

Upvotes: 3

Related Questions