3

I create a component with ListView under the structure: TabBarIOS > NavigatorIOS > ListView. I try to fetch data in componentDidMount(). But it didn't work unless I fetch it in componentWillMount(). Why?

I've put my work here https://github.com/chiakie/MyAwesomeProject
In MotorcycleList.js, componentDidMount() seem to never be called.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Chiakie
  • 271
  • 1
  • 2
  • 12
  • try showing your work do we can be more helpful – Chris Geirman Dec 23 '15 at 07:09
  • @ChrisGeirman Sorry, I've update the post to provide more detail about my work. Thanks for your opinions. – Chiakie Dec 24 '15 at 03:03
  • great that you link of to your repo for more detail, but best practice is to put actual code in your post for two reasons. 1) it preserves the issue with example for all those who may find this question in the future. 2) less friction for those wanting to help. still, providing a link to the repo is great for more info if needed. – Chris Geirman Dec 24 '15 at 06:50
  • To let everyone understand the structure of components, I choose to post the whole repo instead of code pieces. Thanks for your advice:) – Chiakie Dec 24 '15 at 09:48
  • @Chiakie - you can do both! The best thing to do would be post the relevant pieces of code and also a link to the repo as an extra. – Tom Jan 15 '17 at 10:49

1 Answers1

2

The componentWillMount() life cycle event is actually the correct place to call fetchData() because it is invoked once before the component mounts, this way you can setState do that the data is there when it mounts.

Mounting: componentWillMount

void componentWillMount()

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method,render() will see the updated state and will be executed only once despite the state change.

Whereas componentDidMount() renders after the component had already mounted.

Mounting: componentDidMount

void componentDidMount()

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The componentDidMount() method of child components is invoked before that of parent components.

Community
  • 1
  • 1
Chris Geirman
  • 9,474
  • 5
  • 37
  • 70
  • It ls weird that the code within componentDidMount() works again. You are right, the best place is put fetchData() in componentWillMount(). – Chiakie Dec 24 '15 at 09:44
  • 10
    No. Actually it's really bad to perform async tasks in `componentWillMount`. An async function may take several seconds. The rendering is blocked for that time. It's best practice to fetch data in `componentDidMount`. You can show a loading spinner while fetching data. – Pawel Aug 14 '18 at 08:37