React Fetching Data using Fetch API and Axios Step by step Implementation and Top 10 Questions and Answers
 Last Update:6/1/2025 12:00:00 AM     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    18 mins read      Difficulty-Level: beginner

React Fetching Data Using Fetch API and Axios

Data fetching is a crucial aspect of modern web applications, especially when building single-page applications (SPAs) with frameworks like React. React components can be enhanced by fetching data from remote servers, which can be achieved through several methods, among them the Fetch API and Axios library. Both provide means to send HTTP requests to web servers from your React application and are widely used because of their simplicity and powerful functionalities.

Fetch API

The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest (XHR) but with a more powerful and flexible feature set, built on top of Promises. It supports different types of network requests including GET, POST, PUT, DELETE, etc., and can handle JSON or other types of data formats efficiently.

Making a GET Request

To fetch data from an API, the most common request type, you can use fetch() function as follows:

import React, { useEffect, useState } from 'react';

function DataFetchingComponent() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetch('https://api.example.com/data')
            .then(response => response.json()) // parse JSON from the response body
            .then(data => {
                setData(data); // update state with fetched data
                setLoading(false); // set loading state to false after data is fetched
            })
            .catch(error => {
                setError(error); // update the error state if there is an error
                setLoading(false); // also set loading state to false after error
            });
    }, []); // empty dependency array means this effect runs only once after component mounts

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <div>
            <h1>Data:</h1>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
}

export default DataFetchingComponent;

In this example, we create a React component that fetches some data from https://api.example.com/data when it mounts. The useEffect hook manages the side effect of fetching data, which includes updating the state based on the response. This keeps the UI in sync with the data received from the server.

Important Features of Fetch API:
  • Built-in Support: Since Fetch API is part of the browser's native JavaScript, no additional libraries need to be installed, making it easy to get started.
  • Promise-Based Interface: Fetch API uses Promises, providing a more modern and cleaner syntax to handle asynchronous operations compared to traditional callback-based approaches.
  • Stream Processing: Unlike XHR which buffers the entire response before processing, Fetch API supports streaming, allowing partial processing of data as it arrives over the network.
  • No Browser Support Issues: While older browsers may not support Fetch API natively, polyfills can be used to extend support to those browsers.
Limitations of Fetch API:
  • No Automatic Parsing: Fetch API does not automatically parse the response body; you need to explicitly call .json(), .text(), etc., to convert it into JavaScript objects.
  • Verbosity: Managing error handling, retry mechanisms, timeouts, and other complexities often require additional boilerplate code.
  • Browser Compatibility: Although mostly supported, some older browsers might still require polyfills.

Axios Library

Axios is a promise-based HTTP client for the browser and Node.js. It is one of the most popular libraries for making network requests due to its simplicity and ease of use. Axios provides automatic JSON serialization and deserialization, and offers more powerful features out-of-the-box without requiring additional code.

Making a GET Request with Axios

First, install axios using npm or yarn:

npm install axios
# or
yarn add axios

Then, you can use it in your component as shown below:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function DataFetchingComponent() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        axios.get('https://api.example.com/data')
            .then(response => {
                setData(response.data); // automatically parse JSON data via Axios
                setLoading(false);
            })
            .catch(error => {
                setError(error);
                setLoading(false);
            });
    }, []);

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <div>
            <h1>Data:</h1>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
}

export default DataFetchingComponent;

Just like with Fetch API, we manage data fetching inside the useEffect hook in this example. However, Axios simplifies the process by automatically parsing JSON data.

Important Features of Axios:
  • Automatic JSON Serialization/Deserialization: Axios automatically converts JSON responses to JavaScript objects and vice versa when making HTTP requests, reducing boilerplate.
  • Error Handling: Axios provides a straightforward way to handle errors through catch(). It simplifies distinguishing between HTTP errors and other kinds of exceptions.
  • Interceptors: Axios allows intercepting requests or responses before they are handled by then() or catch(). This is useful for adding headers, authentication tokens, or logging.
  • Concurrency: Axios can handle concurrent requests easily, making it better suited for complex applications where multiple API calls are necessary simultaneously.
Limitations of Axios:
  • Additional Library Requirement: Unlike Fetch API, Axios needs to be installed and imported separately, adding another dependency.
  • Complex Configuration: While Axios simplifies many tasks, configurations for advanced scenarios can become more complicated compared to the native Fetch API.
  • Learning Curve: For developers new to React or data fetching in JavaScript, understanding how to use Axios effectively requires some initial learning effort.

Choosing Between Fetch and Axios

Deciding whether to use fetch or axios comes down to your specific requirements and preferences:

  • For Simple Applications: If your application doesn't require extensive features and your main concern is minimizing dependencies, then Fetch API might be enough.
  • Enhanced Features: When dealing with cross-cutting concerns such as request and response interceptors, authentication, or handling different data formats (like FormData), Axios provides a convenient solution.
  • Project Requirements: Some projects may have established practices around specific libraries. If your project already uses Axios, sticking with it can promote consistency and potentially reap the benefits of shared knowledge among team members.

In conclusion, both Fetch API and Axios are valuable tools for fetching data in React applications. Fetch API leverages built-in browser capabilities, while Axios offers extended functionality with less code complexity. Understanding both and applying them appropriately based on your project's needs will enhance your ability to build robust and efficient web applications.




Examples, Set Route and Run the Application Then Data Flow: A Step-by-Step Guide for Beginners on React (Fetching Data using Fetch API and Axios)

Learning how to fetch data in React is a crucial step towards becoming proficient with JavaScript-based web applications. This guide aims to help beginners understand the process of setting routes, running an application, and comprehending the data flow using both the Fetch API and Axios libraries.

Setting Up Your React Application

Before you can fetch data, you need a React application to work with. You can create one using create-react-app as shown below:

  1. Install Node.js: Ensure Node.js and npm (Node Package Manager) are installed on your system. You can download them from nodejs.org.

  2. Create a New React App: Open your terminal or command prompt and run the following command:

    npx create-react-app data-fetching-example
    
  3. Navigate to Your App Directory: Enter the newly created project directory.

    cd data-fetching-example
    
  4. Start Your Development Server: Run the following command to start your React app:

    npm start
    

    Your app will now be running at http://localhost:3000.

Setting Routes

React Router is the standard library for routing in a React application. Let's set up basic routing before fetching data.

  1. Install React Router: Still in the project directory, install the react-router-dom package:

    npm install react-router-dom
    
  2. Configure Routing: Modify your src/App.js file to include routes.

    import React from 'react';
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    import FetchApiData from './FetchApiData';
    import AxiosData from './AxiosData';
    
    function App() {
        return (
            <Router>
                <div>
                    <h1>Data Fetching Example</h1>
                    <Switch>
                        <Route path="/fetch-api" component={FetchApiData} />
                        <Route path="/axios" component={AxiosData} />
                    </Switch>
                </div>
            </Router>
        );
    }
    
    export default App;
    
  3. Create Components: Create two new files, FetchApiData.js and AxiosData.js, in the src folder.

    FetchApiData.js:

    import React, { useEffect, useState } from 'react';
    
    function FetchApiData() {
        const [data, setData] = useState([]);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(null);
    
        useEffect(() => {
            fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response => response.json())
                .then(json => {
                    setData(json);
                    setLoading(false);
                })
                .catch(error => {
                    setError(error);
                    setLoading(false);
                });
        }, []);
    
        if (loading) return <p>Loading...</p>;
        if (error) return <p>Error: {error.message}</p>;
    
        return (
            <ul>
                {data.map(post => (
                    <li key={post.id}>{post.title}</li>
                ))}
            </ul>
        );
    }
    
    export default FetchApiData;
    

    AxiosData.js:

    First, install Axios.

    npm install axios
    

    Now, create the AxiosData component.

    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    function AxiosData() {
        const [data, setData] = useState([]);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(null);
    
        useEffect(() => {
            axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                    setData(response.data);
                    setLoading(false);
                })
                .catch(error => {
                    setError(error);
                    setLoading(false);
                });
        }, []);
    
        if (loading) return <p>Loading...</p>;
        if (error) return <p>Error: {error.message}</p>;
    
        return (
            <ul>
                {data.map(post => (
                    <li key={post.id}>{post.title}</li>
                ))}
            </ul>
        );
    }
    
    export default AxiosData;
    

Running the Application

With everything set up correctly, ensure your development server (npm start) is still running.

  • Access Fetch API Example: Navigate to http://localhost:3000/fetch-api in your browser. You should see a list of blog post titles fetched via the Fetch API.

  • Access Axios Example: Navigate to http://localhost:3000/axios. Similarly, this page will display a list of blog post titles fetched via Axios.

Understanding the Data Flow

Whether you use the Fetch API or Axios, the data fetching process follows a similar pattern.

  1. State Initialization: At the beginning, you define states to store data, loading status, and error messages.

  2. useEffect Hook: Utilize the useEffect hook from React for side effects like data fetching. It runs once when the component mounts, thanks to the empty dependency array [].

  3. Data Fetching:

    • Fetch API: Use the global fetch() function to request data from an endpoint. It returns a promise that resolves with the response object.
    • Axios: Make requests using axios.get(url). It also returns a promise but provides more features and better handling of responses and errors out of the box.
  4. Handling Responses: Convert the response to JSON (for Fetch API) or access the data directly (Axios). Update the state to contain the fetched data.

  5. Error Handling: Catch any errors that might occur during the fetching process and update the error state accordingly.

  6. Conditional Rendering: Based on the loading state and presence of an error, render different elements to reflect the fetching stage to the user (e.g., loading spinners, error messages).

Conclusion

By following the steps above, you can successfully implement data fetching in a React application using both the Fetch API and Axios. Practice these concepts to solidify your understanding and apply them to more complex projects. React's robust ecosystem makes data handling intuitive and flexible, especially once you're comfortable with its hooks and routing system.




Certainly! Here are the top 10 questions and answers related to Fetching Data using Fetch API and Axios in React:

1. What is the difference between Fetch API and Axios?

Fetch API is a modern built-in JavaScript interface that allows developers to make web requests easily and asynchronously. It provides a global fetch() method to initiate network requests.

Axios is a widely used, third-party promise-based HTTP client that works both in the browser and on Node.js. It simplifies HTTP requests and supports features such as request and response interceptors.

Key Differences:

  • Ease of Use: Axios has a simpler API and is more developer-friendly.
  • Interceptors: Axios supports request and response interceptors which can be very useful for global configuration and error handling.
  • Browser Support: Fetch API is supported in all modern browsers but requires additional polyfills for older browsers.
  • Error Handling: Fetch API does not reject the promise on HTTP error statuses, while Axios will reject the promise for HTTP status codes outside the range of 2xx.

2. How do you fetch data using the Fetch API in React?

To fetch data using Fetch API in React, you can use the fetch() function within a component's lifecycle method (componentDidMount) or within a functional component using the useEffect hook.

Example in a Functional Component:

import React, { useEffect, useState } from 'react';

function FetchDataExample() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default FetchDataExample;

3. How do you fetch data using Axios in React?

Axios makes it easier to perform HTTP requests. It automatically transforms JSON data and has a simple API.

Example in a Functional Component:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function AxiosDataExample() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default AxiosDataExample;

4. How can you handle errors gracefully in Fetch API and Axios?

Fetch API:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('Data:', data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Axios:

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    console.log('Data:', response.data);
  })
  .catch(error => {
    console.error('There was a problem with the Axios request:', error);
  });

5. How do you implement an HTTP POST request using Fetch API and Axios in React?

Fetch API:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch((error) => console.error('Error:', error));

Axios:

axios.post('https://jsonplaceholder.typicode.com/posts', {
  title: 'foo',
  body: 'bar',
  userId: 1,
})
.then(response => console.log('Success:', response.data))
.catch(error => console.error('Error:', error));

6. How can you set headers globally using Axios in React?

You can set headers globally in Axios using axios.defaults.

axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');
axios.defaults.baseURL = 'https://api.example.com';

axios.get('/endpoint')
  .then(response => console.log('Data:', response.data))
  .catch(error => console.error('Error:', error));

7. How do you use interceptors with Axios?

Interceptors can be used to intercept requests or responses before they are handled by .then() or .catch().

Request Interceptor:

axios.interceptors.request.use(
  config => {
    console.log('Request Config:', config);
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
    return config;
  },
  error => {
    console.error('Request Error:', error);
    return Promise.reject(error);
  }
);

Response Interceptor:

axios.interceptors.response.use(
  response => {
    console.log('Response:', response);
    return response;
  },
  error => {
    console.error('Response Error:', error);
    return Promise.reject(error);
  }
);

8. How do you cancel a request in Fetch API and Axios?

Fetch API:

const controller = new AbortController();
const signal = controller.signal;

fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => response.json())
  .then(data => console.log('Data:', data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', error);
    }
  });

// To cancel the request:
controller.abort();

Axios:

const source = axios.CancelToken.source();

axios.get('https://jsonplaceholder.typicode.com/posts', {
  cancelToken: source.token
})
.then(response => console.log('Data:', response.data))
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  } else {
    console.error('Error:', error);
  }
});

// To cancel the request:
source.cancel('Request canceled by the user.');

9. What are the advantages of using Axios over Fetch API?

  • Simpler API: Axios has a more straightforward API compared to Fetch API.
  • Automatic JSON Transformation: Axios automatically transforms JSON data.
  • Browser and Node.js Support: Axios works seamlessly in both environments.
  • Features like Interceptors: Axios provides features like request and response interceptors, making it more flexible.
  • Error Handling: Axios rejects the promise for HTTP errors, while Fetch API only rejects on network errors.

10. How do you handle CORS issues when using Fetch API and Axios?

CORS (Cross-Origin Resource Sharing) issues arise when a web page attempts to request a resource from a different domain than the one that served the web page.

Handling CORS:

  1. Server-Side Configuration: Ensure that the server is configured to allow cross-origin requests. This involves setting appropriate CORS headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, etc.).

  2. Proxy Setup: For development purposes, you can set up a proxy server. In Create React App, you can specify a proxy in package.json to forward API requests to the backend server.

    "proxy": "http://localhost:5000"
    
  3. Using CORS Proxy: For quick testing, you can use a CORS proxy server like https://cors-anywhere.herokuapp.com/ (useful only for development).

Remember, addressing CORS issues should ideally be handled on the server side for production applications.

By understanding these key points, you can effectively use the Fetch API and Axios to manage data fetching in your React applications.