Jacquob Cast
Jacquob Cast

Reputation: 156

Can we do a If in Axios - ReactJS

I'm writing this post because i would like to know if it's possible to do a if in axios. Basically i'm trying to send only variables with contents with axios.

I have a code globally like this :

 async handleSubmit(event) {
  this.setState({ loading: true });

  setTimeout(() => {
   this.setState({ loading: false });
  }, 2000);

 event.preventDefault();
 const {
   name_contact='', name_contact1='', endfr='', endfr_1='',
 } = this.state;


 const name = [name_contact, name_contact1].filter(v =>v).join(',');
 const end = [name_contact, name_contact1].filter(v =>v).join(',');

 await axios.post(
  ' MY_endpoint API',
  {
    name, end
  })
}

For example if name_contact and name_contact1 are empty, i'm going to receive name="" with my axios.post. But i'm trying to delete name or end if they're empty for axios.post to send only what is useful and not a completely empty variable.

So I tell myself that I could do an if in axios to check the content of a variable and send it if there is content.

Upvotes: 0

Views: 101

Answers (3)

Rafael Hovsepyan
Rafael Hovsepyan

Reputation: 781

More generic way to not explicitly check each field

const payload = {name, end, /*other fields*/};

//filtering not empty fields
const result = Object
.keys(payload)
.filter(key => payload[key] !== '')
.reduce((result, key) => ({...result, [key]: payload[key]}), {});

// Or just use Lodash _.pickBy
const result = _.pickBy(payload, field => field !== '');

await axios.post('MY_endpoint API', result);

Upvotes: 2

Rakesh T.R
Rakesh T.R

Reputation: 362

you can do like this

var dataToSend={};

if(name!="" &&end!=""){
dataToSend={name,end}
}

// Send a POST request
axios({
  method: 'post',
  url: '/user',
  data: dataToSend
});

Upvotes: 0

Andres
Andres

Reputation: 1012

It's not related to axios. Just add items to data object conditionally:

await axios.post(
  ' MY_endpoint API',
  {
    ...(name && { name }),
    ...(end && { end })
  })
}

Also lodash can help you here:

await axios.post(
  ' MY_endpoint API',
  _.pickBy({
    name, end
  }, Boolean))
}

Upvotes: 2

Related Questions