javascript - Making request parameter optional in axios get request - Stack Overflow

I have below axios request.import axios from 'axios';axios.get('user', {params:

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.

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.

Share Improve this question asked Nov 18, 2021 at 10:42 Shruti sharmaShruti sharma 2119 gold badges33 silver badges92 bronze badges 1
  • 2 you can see this post. I think you got your answer from this. stackoverflow./questions/52312919/… – Mitali Patel Commented Nov 18, 2021 at 10:51
Add a ment  | 

2 Answers 2

Reset to default 4

think u are looking for something like below:

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

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);
})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744843121a4596677.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信