I am calling an API before mounting a ponent but my code calling an API twice. My requirement is to display year data after getting Successful API call(it will return year data). If I use setState function inside ponentWillMount then it should not call render method, but in my case render function is also called several times.
ponentWillMount(){
// Year api call
var oauth=GetAuthToken()
if(this.props.options.apiName === 'year__c' ){
var access_token=oauth.then((data) => {
var temp
temp=GetYear(data.access_token)
temp.then((obj) => {
this.setState({
year:obj
})
})
})
}
}
I am calling an API before mounting a ponent but my code calling an API twice. My requirement is to display year data after getting Successful API call(it will return year data). If I use setState function inside ponentWillMount then it should not call render method, but in my case render function is also called several times.
ponentWillMount(){
// Year api call
var oauth=GetAuthToken()
if(this.props.options.apiName === 'year__c' ){
var access_token=oauth.then((data) => {
var temp
temp=GetYear(data.access_token)
temp.then((obj) => {
this.setState({
year:obj
})
})
})
}
}
ponentWillMount
function since it will NOT trigger a re-render. Instead I use the ponentDidMount
function for this.
– Fizz
Commented
Dec 12, 2016 at 21:46
The problem you are running into is that your setting state based off a promise being resolved. In a normal ponentWillMount
you setState, it updates the state, and then render() is called for the first time. When you introduce asynchronous api calls into the picture, then what happens is:
ponentWillMount
is executed, an API call is made and a Promise is created, while the Promise waits to be resolved code continues executing, React executes the Render() method on the ponent. At some point after rendering the Promise is resolved, setState is then called and since the Component has already been rendered then it will have to rerender due to a change in state.
The primary difference between the two being: If you just setState
in the ponentWillMount
then it will happen before render occurs. If you have setState
as part of a Promise being resolved, it will happen after the ponent has rendered thus causing multiple renders.