reactjs - React parent renders with initial state before successful ajax call sets state -


i'm using react webpack , babel compiling jsx. have parent component looks this:

const menu = module.exports = react.createclass({     loaduser() {         let xhr = new xmlhttprequest();         xhr.open('get', this.state.url, true);         xhr.onload = function() {             let data = json.parse(xhr.responsetext);             this.setstate({                 user: data             });         }.bind(this);         xhr.send();      },       componentdidmount() {          this.loaduser();      },       getinitialstate() {          return {              url: this.props.url,              user: []          };      },      render: function() {          return (             <div classname="menu">                  <nav user={this.state.user} />                       ...             </div>         );     }  }); 

as can see, attempt use this.setstate(...) set this.state.user data received xmlhttprequest. however, when try access in child, nav, calling, console.log(this.props.user), empty array, i.e. [], printed.

what doing wrong here? i've read react docs , i'm stumped. in following tutorial, data fetched server , transferred child component in manner similar i've done (above). appreciated. if need supply additional code or context, let me know. thanks.

getinitialstate used @ first renderso it's normal it's complete before ajax call since ajax call performed in componentdidmount triggered after first rendering.

before ajax call empty state.user empty, when data received should update view new data.

in opinion you're not doing wrong depends on want do. example put message in getinitialstate mgs:"please wait data fetching" , remove msg when data arrive.

otherwise if absolutely need data ready before rendering component can use : https://facebook.github.io/react/tips/props-in-getinitialstate-as-anti-pattern.html read may not fit use.

talking myself put loading msg in getinitialstate , proceed way do.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -