Ad

React: Updating Property Of Object In State

- 1 answer

I have a component that tracks documents as state, aDocuments. When a button is clicked, the document is uploaded. Each document object contains the functionality to handle the upload. During the upload, a mode in the document is changed from new to uploading to done. The document object updates the mode during the upload. Each document is a reference from an object in the aDocuments array which is in my state.

How do I properly handle updating properties of an object in state, when that object can update itself? My setState calls do nothing but cause a render.

Doc.prototype.upload = function (uploadComplete) {
  if (this.mode === 'new') {
    this.mode = 'uploading';
    // do uploading stuff and call uploadComplete after upload is finished
    $.ajax(..., complete: function() {
      this.mode = 'done';
      uploadComplete(this); 
    });
  }
}

// in my component
clickHandler: function (doc) {

  doc.upload(function(tmpDoc) {
    // this will cause render to show the doc as done
    this.setState('aDocuments', this.state.aDocuments);
  });

  // this will show the document as uploading
  this.setState('aDocuments', this.state.aDocuments);
}

Any help would be greatly appreciated.

Ad

Answer

In order to update the state of the top-level component where your documents array lives, you need to pass a callback function via props (which modifies the top-level documents array) to the individual document components.

Ad
source: stackoverflow.com
Ad