0

I have a code in reactjs which sends datas entered in a form using axios. And it works fine. You have below a code with the same architecture as mine.

export default class FormPage extends Component {
     constructor(props) {
      super(props);
      this.state = initialState;
      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleChange = this.handleChange.bind(this);
     }

     showMessage = (bool) => {
      setTimeout(() => {
       this.setState({
        showMessage: true
       });
      }, 2000);
     if (this.state.Showing) return;
      this.setState({ Show: true, Showing: true });
     setTimeout(() => {
      this.setState({ Show: false, Showing: false });
      }, 2000);
     }

     showMessageFalse = (bool) => {
      this.setState({
       showMessage: false
       });
      this.setState(initialState);
     }

     handleChange(event) {
      const InputValue = event.target.value;
      const stateField = event.target.name;
      this.setState({
        [stateField]: InputValue,
      });
      console.log(this.state);
     }

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

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

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

     await axios.post(
      ' MY_endpoint API',
      {
        name: `${name_contact}`);
      }

  render() {

    const { loading } = this.state;

    return (
      <div>

        <ExpansionPanel title="Contacts" expandedTitle="Contacts" titleIcon="done_all" ><div>
          <Container>
            <div id="normal"><label id='title2'>Detail du contact</label></div><br/>
              <Row align="center">
                <Col id= "color" sm={3}> <label> Name: </label></Col> <Col id= "color" sm={3}><Input placeholder="Nom complet" type="string" name="name_contact" value={this.state.name_contact} onChange={this.handleChange}/><br /> </Col>
              </Row>
          </Container>
          </div>
        </ExpansionPanel>

      <form onSubmit={this.handleSubmit}>
      <br /><br /><div id="deb"><Button type="submit" value="Show" onClick={this.showMessageFalse.bind(null, true)} > Update </Button></div>
      </form>
    </div>
    );
  }
}

But on my real code, I have a lot of datas to send because i have a lot of field. I would like to know if it was possible to send with this architecture, only the fields where a variable is in.

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

 await axios.post(
  ' MY_endpoint API',
  {
    name: `${name_contact}`);
  }

i want for example, if my name_contact is not filled and I click on "Update", it does not send the name_contact field, but if it is filled, it sends it.

If it’s possible to do something like that, what am I supposed to use? Thanks

Jacquob Cast
  • 156
  • 1
  • 12
  • 1
    you can use the FormData api to conditionally remove fields – TKoL Dec 11 '19 at 10:45
  • Oh, I see you're not using a Form to send to the api anyway, you're just using a raw object. In that case, it's way easier! Just iterate over all your keys, and if a value is blank, delete the key from the object! – TKoL Dec 11 '19 at 10:45
  • @TKoL but How can I know in advance what value will be put in the axios get? Because i'm adding ALL the datas in my axios.get – Jacquob Cast Dec 11 '19 at 10:49
  • So prepare your object BEFORE your request goes out, and then put the data in the request after the data is prepared. – TKoL Dec 11 '19 at 10:49
  • I've edited my answer to show that you can prepare your data, and then post it after it's been prepared. – TKoL Dec 11 '19 at 10:52

1 Answers1

0

Prepare the object you're going to post, iterate over the keys, and delete any empty field:

 var data = {
    name: 'x',
    position: 'y',
    gender: ''
  }

  Object.keys(data).forEach(key => {
    if (!data[key]) delete data[key];
  })

  console.log(data);

  await axios.post(
      ' MY_endpoint API',
      data)

The way I've implemented it only checks for falsy values so be careful of that. A value of '0' will be truthy but a value of 0 will be falsy

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • It seems to work. Well, then I have a big problem on the send because i was sending like that "name: `${name_contact}`), obj: `${obj_form, obj_text}`)". I’m not validating right now to see if other people have any ideas, but I’ve gone very well with your help – Jacquob Cast Dec 11 '19 at 11:00
  • Sorry, I don't understand what problem you're having. You're saying you want to add a validation step before you send it out? – TKoL Dec 11 '19 at 11:01
  • 1
    @NatkoUndoshy at this point, at least, have you successfully gotten the `data` to not send empty values? – TKoL Dec 11 '19 at 11:02
  • Overall, I manage to delete the empty data thanks to your technique. Now I would like that in axios, if the data is non-existent, axios does not take them. For example i have this in my axios.post "name: `${name_contact}`, `${name_contact_1}`)". I would like that if name_contact_1 is non-existent (removed by your technique), axios see only "name: `${name_contact}`)". Basically it's not my initial question, So you don’t have to try to see if it’s possible if you don't want – Jacquob Cast Dec 11 '19 at 11:09
  • 1
    I'm having a hard time understanding in the comments, I think you should ask a new question and link me in the comments here to your new question – TKoL Dec 11 '19 at 11:53
  • i made a new question (and i don't know how to tag) so If you have time today, I’d like your help – Jacquob Cast Dec 11 '19 at 14:15