javascript - React component not re-rendering on state change -


i have react class that's going api content. i've confirmed data coming back, it's not re-rendering:

var dealslist = react.createclass({   getinitialstate: function() {     return { deals: [] };   },   componentdidmount: function() {     this.loaddealsfromserver();   },   loaddealsfromserver: function() {     var newdeals = [];      chrome.runtime.sendmessage({ action: "finddeals", personid: this.props.person.id }, function(deals) {       newdeals = deals;     });      this.setstate({ deals: newdeals });   },   render: function() {     var dealnodes = this.state.deals.map(function(deal, index) {       return (         <deal deal={deal} key={index} />       );     });     return (       <div classname="deals">         <table>           <thead>             <tr>               <td>name</td>               <td>amount</td>               <td>stage</td>               <td>probability</td>               <td>status</td>               <td>exp. close</td>             </tr>           </thead>           <tbody>             {dealnodes}           </tbody>         </table>       </div>     );   } }); 

however, if add debugger below, newdeals populated, , once continue, see data:

  loaddealsfromserver: function() {     var newdeals = [];      chrome.runtime.sendmessage({ action: "finddeals", personid: this.props.person.id }, function(deals) {       newdeals = deals;     });     debugger     this.setstate({ deals: newdeals });   }, 

this what's calling deals list:

var gmail = react.createclass({   render: function() {     return (       <div classname="main">         <div classname="panel">           <dealslist person={this.props.person} />         </div>       </div>     );   } }); 

that's because response chrome.runtime.sendmessage asynchronous; here's order of operations:

var newdeals = [];  // (1) first chrome.runtime.sendmessage called, , *registers callback* // when data comes *in future* // function called chrome.runtime.sendmessage({...}, function(deals) {   // (3) sometime in future, function runs,   // it's late   newdeals = deals; });  // (2) called immediately, `newdeals` empty array this.setstate({ deals: newdeals }); 

when pause script debugger, you're giving extension time call callback; time continue, data has arrived , appears work.

to fix, want setstate call after data comes chrome extension:

var newdeals = [];  // (1) first chrome.runtime.sendmessage called, , *registers callback* // when data comes *in future* // function called chrome.runtime.sendmessage({...}, function(deals) {   // (2) sometime in future, function runs   newdeals = deals;    // (3) can call `setstate` data   this.setstate({ deals: newdeals }); }.bind(this)); 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -