简体   繁体   中英

React.js render before fetch is done

Okay i have a problem that my app goes into an render before my fetch is done so it renders wrong

here is the code

componentWillMount() {     
  fetch('http://localhost:8081/milltime/login?users='+this.state.email, {

})
    fetch("http://localhost:8081/milltime/getUsers")
      .then(res => res.json())
      .then(info => {
        this.setInfo(info);
          for (var i = 0; i < info['mta:getUsersResponse']['mta:users'].length; i++) {
            const user = {
              id: info['mta:getUsersResponse']['mta:users'][i]['mta:UserId'],
              username: info['mta:getUsersResponse']['mta:users'][i]['mta:UserLogin'],
              name: info['mta:getUsersResponse']['mta:users'][i]['mta:FullName']
          }

          this.addUser(user); 
        }
  }).then(function() {
            console.log("signed in to milltimes");
        }).catch(function() {
            console.log("need to sign in to milltime");
        });

}

setInfo(info) {
    this.setState({
      info: info,
  })
}
     render() {
    if (!this.state.info) {
      return (
              <MilltimeLogin email={this.state.email}/>
     );  
    } 

  return(

 <div className="usersTable">
   <Table striped bordered condensed responsive hover>
     <thead>
     <tr>
     <th/>
      <th className="title">Employees</th>
      <th/>
      </tr>
       <tr>
        <th>Id</th>
        <th>Full Name</th>
        <th>Username</th>
       </tr>
     </thead>
       <tbody>
          {
            Object
              .keys(this.state.Users)
              .map(key => <User key={key} index={key} details={this.state.Users[key]} onChange={this.props.onChange} />)
          }
       </tbody>
   </Table>
 </div>

  );
}
}

The problem here is that the second fetch /getUsers need a session key that the first fetch provides to work otherwise it will give an error that its missing session. And because it for some reason doesnt get this session key it doesnt set info so the render function will go into the if statement and render MilltimeLogin component instead of the rest. Anyone know how to make sure the first fetch is all done so the second one get the session key.

EDIT if i reload the page one time it works but thats not how i want it

Fetch is asynchronous as you can read here so nothing assure you that the first fetch will be over when your second one is starting.
Maybe the await prefix can help you there (read this for more information) Hope this helps you in your research

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