Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState inside promise.all() react

I have a small crud application I am trying to build and output some data onto. I have to make 3 different api calls which each return a promise and through that I am trying to assign each return promise in its own state.

export default class TableExampleControlled extends Component {

state = {
 rentalsData: [],
 driversData: [],
 vehiclesData: [],
};

componentDidMount() {
 Promise.all([rentals(), drivers(), vehicles()])
 .then((rentalsData,driversData, vehiclesData) => {
   this.setState({ rentalsData,driversData, vehiclesData });
   console.log(this.state)
});
};
render() {     
 const rentalEntries = this.state.rentalsData
 const tableRow = rentalEntries.map((data) =>
 <TableRow selected={this.isSelected(0)}>
    <TableRowColumn key={data.status}>{data.status}</TableRowColumn>
    <TableRowColumn key={data.vehicle}>{data.vehicle}</TableRowColumn>
    <TableRowColumn key={data.driver}>{data.driver}</TableRowColumn>
    <TableRowColumn key={data.email}>{data.email}</TableRowColumn>        
    <TableRowColumn key={data.start_date}>{data.start_date}</TableRowColumn>
    <TableRowColumn key={data.end_date}>{data.end_date}</TableRowColumn>
    <TableRowColumn key={data.rate}>{data.rate}</TableRowColumn>
  </TableRow >
);
like image 549
Pat Lopes Avatar asked Dec 18 '22 02:12

Pat Lopes


2 Answers

I see two problems in your example. Promise.all resolves into a single variable which is an array. The elements of this array are the results of your calls. So:

.then(result => {
  const [ rentalsData, driversData, vehiclesData ] = result;

  this.setState({ rentalsData,driversData, vehiclesData });  
});

Also you can't see the state immediately when you call setState because that method is asynchronous. If you wanna do it try:

this.setState({ rentalsData,driversData, vehiclesData }, () => {
  console.log(this.state);
});
like image 117
Krasimir Avatar answered Dec 28 '22 23:12

Krasimir


Promise.all resolves your promises into an array of results, change your .then to take this array, and then you can access its results using array syntax:

Promise.all([rentals(), drivers(), vehicles()])
 .then((results) => {
   this.setState({ 
     rentalsData: results[0],
     driversData: results[1], 
     vehiclesData: results[2] 
   });
});
like image 35
linasmnew Avatar answered Dec 28 '22 23:12

linasmnew