Reputation: 10441
I'm new to reactjs framework and I have a bit of confusion if what is the right way in listening if state change after an API call.
use then
and catch
after calling an action
via componentDidUpdate
:
componentDidMount(){
this.props.getHero(this.props.params.id).then((result) => {
this.props.initialize({
"name":result.name,
"description": result.description
});
})
.catch(error => {
});
}
or via componentWillUpdate
// Call the getHero action (API)
componentDidMount(){
this.props.getHero(this.props.params.id);
}
// Then listen if the state change via `mapToStateProps`
componentDidMount(){
this.props.getHero(this.props.params.id);
}
componentWillUpdate(){
this.props.initialize({
"name":this.props.heroes.name,
"description": this.props.heroes.description
});
}
Upvotes: 0
Views: 243
Reputation: 20027
Listen for changes in componentWillUpdate
componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
Load data in componentDidMount
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
Upvotes: 2