Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  152] [ 2]  / answers: 1 / hits: 19723  / 7 Years ago, sat, april 1, 2017, 12:00:00

I'm working on react for last 1 year. The convention which we follow is make an API call in componentDidMount, fetch the data and setState after the data has come. This will ensure that the component has mounted and setting state will cause a re-render the component but I want to know why we can't setState in componentWillMount or constructor



The official documentation says that :




componentWillMount() is invoked immediately before mounting occurs. It
is called before render(), therefore setting state in this method will
not trigger a re-rendering. Avoid introducing any side-effects or
subscriptions in this method.




it says setting state in this method will not trigger a re-rendering, which I don't want while making an API call. If I'm able to get the data and able to set in the state (assuming API calls are really fast) in componentWillMount or in constructor and data is present in the first render, why would I want a re-render at all?



and if the API call is slow, then setState will be async and componentWillMount has already returned then I'll be able to setState and a re-render should occur.



As a whole, I'm pretty much confused why we shouldn't make API calls in constructor or componentWillMount. Can somebody really help me understand how react works in such case?


More From » reactjs

 Answers
6

1. componentWillMount and re-rendering



Compare this two componentWillMount methods.

One causes additional re-render, one does not



componentWillMount () {
// This will not cause additional re-render
this.setState({ name: 'Andrej '});
}

componentWillMount () {
fetch('http://whatever/profile').then(() => {
// This in the other hand will cause additional rerender,
// since fetch is async and state is set after request completes.
this.setState({ name: 'Andrej '});
})
}


.

.

.

2. Where to invoke API calls?



componentWillMount () {
// Is triggered on server and on client as well.
// Server won't wait for completion though, nor will be able to trigger re-render
// for client.
fetch('...')
}

componentDidMount () {
// Is triggered on client, but never on server.
// This is a good place to invoke API calls.
fetch('...')
}


If you are rendering on server and your component does need data for rendering, you should fetch (and wait for completion) outside of component and pass data thru props and render component to string afterwards.


[#58312] Wednesday, March 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylee

Total Points: 60
Total Questions: 119
Total Answers: 101

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;