0

I am trying to have an optional field on object. If the state variable equals active, I want to have data.fields equal to show. If state does not equal active, I don't want terms to even be part of the data object. The way I have below is my workaround but null still sends which I don't want.

let state = 'active';

let data = {
   name: "John",
   age: 22,
   terms: state === 'active' ? 'show' : null
}

axios.post(url, data);

Is a proper alternative this:

let state = 'active';

let data = {
   name: "John",
   age: 22,
}

if (this.state === 'active') {
   data.terms = 'show';
}

axios.post(url, data);
  • later is proper than above. it's possible to expand object field by `object.field = value` – coding monster Aug 05 '21 at 02:06
  • I just realized I get an error in my console when I do that saying `"property terms does not exist on { name: "john", age: 22}"`. I am also using typescript, which I did not specify originally...will update the question to indicate that –  Aug 05 '21 at 02:09
  • Did you check `this.state === 'active'` is `true`? – coding monster Aug 05 '21 at 02:12

0 Answers0