Friday, November 29, 2024
Google search engine
HomeLanguagesWhere in a React component should you make an AJAX request ?

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:

cd myapp

Project Structure: It will look like the following.

Initial folder structure

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.

App.js




import React, { useState, useEffect } from "react";
  
const App = () => {
  const [text, setText] = useState("Data has not been fetched yet!");
    
  useEffect(() => {
    fetch("https://catfact.ninja/fact")
      .then((response) => response.json())
      .then(({ fact }) => setText(fact))
      .catch((error) => {
        setText("An error occurred!");
      });
  }, []);
    
  return <div>{text}</div>;
};
  
export default App;


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:

npm start

Output:

Every time we reload, the displayed text changes from “Data has not been fetched yet!” to the response data

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments