Where in a React component should you make an AJAX request ?
In most modern web applications, the backend is separated from the frontend. Therefore, it needs to fetch data from a remote endpoint(server), by making AJAX requests.
These AJAX requests should be made after the component has been rendered to the browser, and usually, they need to be made only once. Thus, the best place to make the requests is inside an useEffect hook. Let us take a look at how we can implement this.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app myapp
Step 2: After creating your project folder, i.e. myapp, move to it using the following command:
Project Structure: It will look like the following.
Implementation: Now that we have the project set up, let us replace the content of App.js, located inside the src folder, with the following code.
Step to run the application: Use the following command to run the app in development mode, and open http://localhost:3000 to view it in the browser:
Explanation: Here, we make an AJAX request inside the useEffect hook, taking the help of a free-to-use API. The useEffect hook has a second parameter: an empty array. This array is known as the dependency array, and if any item present in the dependency array changes between successive renders of the component, the code inside that useEffect is executed (there can be more than one useEffect in a component). Thus, an empty dependency array means that the code inside our useEffect will run only once, at first render.
Once we get the response, we change the value of the text variable from “Data has not been fetched yet!” to the response data. Thus we can see that the AJAX request has been made successfully.
Please Login to comment...