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 ?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With