Reputation: 566
I have a React component like this:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
address: '',
phone: ''
}
}
componentDidMount() {
//APIcall1 to get name and set the state
//i.e., axios.get().then(this.setState())
//APIcall2 to get address and set the state
//APIcall3 to get phone and set the state
}
}`
As you can see I am making three API get requests to get the details and setting the state three times after getting the data. Due to this, I am getting this error:
Warning: Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.
By the way, I am not causing a state change in the render method. Anyway to solve this issue?
Upvotes: 1
Views: 2145
Reputation: 9988
In axios you have the method axios.all
:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
Or you can use the standard Promise.all
:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(data => {
// Both requests are now complete
});
Upvotes: 1
Reputation: 33141
As axios.get
returns a promise, you can link them together before calling setState. For example using Promise.all
:
componentDidMount() {
Promise.all([
APIcall1, // i.e. axios.get(something)
APIcall2,
APIcall3
]).then(([result1, result2, result3]) => {
// call setState here
})
}
Just beware that if any of the api calls fail, Promise.all will catch, and setState won't be called.
Upvotes: 5