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 >
);
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);
});
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]
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With