How do I do AJAX requests in React? React itself doesn’t have any allegiance to any particular way of fetching data. Which hook in react is best to fetch the data [constructor, componentdidmount] or have a custom hook [static method].
-
You should use axios library for fetching the data. Here is the link https://www.npmjs.com/package/axios. – parlad May 01 '17 at 11:37
2 Answers
The place you should be calling you AJAX requests depends on your functionality,
If you need you AJAX call when the component is mounted or at repeated interval, you should call it within a
componentDidMount
function. An example could be fetching data a regular intervals from your server to update on screen.If you want to send an AJAX request on an event, you should have it in your custom function. An example could be posting the input values to your backend api
In order to make AJAX calls, you can make use of axios, fetch npm packages

- 270,417
- 55
- 406
- 400
There is not any particular place of fetching AJAX request in React. It depends on your functionality mostly. Until now I've made AJAX calls inside of 'ComponentWillMount' method to make ready data asap.
Also, sometimes I've needed to fetch data from server after a component did mounted. So in that case, I had to use this workaround: React - setState() on unmounted component
The most important topic is here not blocking the rendering interface and to set properly the state, after getting data from server.