Stef1611
Stef1611

Reputation: 2387

reactjs : Fetching external data

I am learning how to use Reactjs and I read the following post : https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data

When componentWillMount is used, it is written that The above code is problematic for both server rendering (where the external data won’t be used) and the upcoming async rendering mode (where the request might be initiated multiple times).

I do not understand :

Upvotes: 0

Views: 84

Answers (2)

danishakh
danishakh

Reputation: 41

According to the React docs, changing your component’s state in componentWillMount will not trigger a re-render. This means that if you make your AJAX call and set the response in your component state, it will not re-render, which means you won’t see your data in the DOM. (Remember that the component was initially created with an initial state which most likely didn’t have the data from your external data/AJAX call response)

You could argue that wouldn’t it be better to do my AJAX call to pull external data before the component mounts for the first time? It wont be better because you don’t know how much time it will take to do your AJAX call. Your AJAX request could take longer to get the data than the time it takes the component to mount and therefore your data does not show up on your DOM as the component has already rendered and there is no re-rendering happening. Your AJAX request could take longer for any reason - your user is on mobile and has slow internet, some issue with your server is making it slow to return responses, etc...

Best thing to do is make your AJAX call in componentDidMount and make your component handle empty data (probably display a loading spinner) until your AJAX request returns the data, sets it to the component state and triggers a re-render! :)

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202836

If you read further down they explain a bit more why componentWillMount is problematic.

The above code is problematic for both server rendering (where the external data won’t be used) and the upcoming async rendering mode (where the request might be initiated multiple times).

But these may be rendered moot as react is essentially deprecating that lifecycle function come react 17, and thus currently is renamed to UNSAFE_componentWillMount and not recommended for use, but instead use componentDidMount to make your async data fetches.

Why does componentDidMount fix this?

Because the server is pre-rendering the components/JSX, but you don't want the component to fetch its data until after it is actually mounted and running in a browser.

react component lifecycle docs

Upvotes: 1

Related Questions