2

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.

Shruti sharma
  • 199
  • 6
  • 21
  • 67
  • 2
    you can see this post. I think you got your answer from this. https://stackoverflow.com/questions/52312919/axios-conditional-parameters – Mitali Patel Nov 18 '21 at 10:51

2 Answers2

3

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);
})
Sid Barrack
  • 1,235
  • 7
  • 17
3

think u are looking for something like below:

params: {
   ...(ID && {
      ID: ID
    }) // conditional spread operator
}
arbitrary_A
  • 333
  • 3
  • 9