最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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);
})
发布评论

评论列表(0)

  1. 暂无评论