简体   繁体   中英

React/Rails field in state not sent to backend in POST request

So I have a field in state bullet_points: [] that is an array of elements.

I have a function in my component that adds/removes elements from this array. To save the changes, clicking submit will sent product: this.state as an argument in a POST request to my backend.

The backend only receives bullet_points if the array IS NOT empty. If I clear the field of all elements, it is never sent to the backend.

What would cause this? Below are the relevant code snippets.

1) Function for add/remove of elements (notice arrow, this is where elements are removed)

  updateList(evt) {
    evt.preventDefault();

    let elements = this.state[evt.target.dataset.type];
    let idx = parseInt(evt.target.dataset.index);
    let new_element = evt.target.dataset.type == "durations" ? 30 : "";

    if (isNaN(idx)) {
      elements.push(new_element);
    } else {
      if (evt.target.dataset.delete) {      <----------
        elements.splice(idx, 1);
      }
      else {
        elements[idx] = evt.target.value;
      }
    }
    this.setState({ [evt.target.dataset.type]: elements });
  }

2) POST request to backend

API.put(`coach/products/${this.props.params.id}`, {
    product: this.state
  }, function(res) {
    this.closeModal();
    Alert.success('<p class="small-body-text">Your changes have been saved</p>', {
      position: "top-right",
      effect: "scale",
      timeout: 5000
    });
  }.bind(this));

Many libraries that serialize and post data do not send key/value pairs if the value is an empty array. For example: jQuery has this behavior . There are essentially two ways you can handle this:

1) On the backend, check for the existence of the key in the post parameters. If it doesn't exist, treat it like an empty array.

2) If you really want to send an empty array (maybe there's a difference between sending an empty array and not sending the key/value at all?), then send the array with a single empty string or some other value that cannot possibly be valid input but that you will check for to mean that the array is empty.

One tricky thing I've run into before - if you're testing with rspec, rspec's post method does not remove the key/value if the value is an empty array; it sends the data as is. So you may want to add additional tests that represent what the client data looks like after it has been serialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM