Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to make an Initial AJAX request from in ReactJS

I have a page where I need to load some initial Ajax data.
I read on this Reactjs page that I should make the call in componentDidMount.

What is the advantage of making the request from componentDidMount rather than componentWillMount ?

like image 892
myusuf Avatar asked May 13 '14 11:05

myusuf


People also ask

Where can you initiate your AJAX requests in React?

it is the best place to fetch data! In this method, we initiate the AJAX request using XMLHttpRequest . We use the GET method and https://programming-quotes-api.herokuapp.com/quotes/page/1 as the endpoint which returns a JSON output of first page quotes.

Where do I make API calls in React?

There are multiple options available to choose from when it comes to making an API request in a React app: Fetch/Axios – The easiest option is to use the Fetch API or use a library like Axios to make API requests.

Which React component lifecycle method is the recommended place to do all your initial AJAX calls?

According to official React docs, the recommended place to do Ajax requests is in componentDidMount which is a lifecycle method that runs after the React component has been mounted to the DOM. It sounds a bit counter intuitive to fully render the component before you even start to fetch data.

Do we need AJAX in React?

React and AJAX are not comparable, but React uses AJAX, or rather you - the developer - use AJAX in React to get data without the page needing to reload.


2 Answers

When using server rendering, componentWillMount is called but componentDidMount is not. Because of this, I tend to do any initialization that requires a browser (including Ajax and DOM manipulation) in componentDidMount.

like image 107
Sophie Alpert Avatar answered Sep 21 '22 14:09

Sophie Alpert


Since react is meant to be used as a view, your ajax requests are supposed to be placed in your model.

Else, if for some reason you need to make it in a view, the difference between componentDidMount and componentWillMount is that the first one is being invoked once the element is re-rendered and you have access to it via this.getDOMNode(), and the second one is invoked once right before render() starts.

like image 37
mms27 Avatar answered Sep 21 '22 14:09

mms27