Home > front end >  Making request parameter optional in axios get request
Making request parameter optional in axios get request

Time:11-18

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.

CodePudding user response:

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

CodePudding user response:

think u are looking for something like below:

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