2 Ways to Fetch Data From API in React JS

How to Fetch Data From API in React JS

In this article, we’re going to learn about how to fetch data from api in react js. Before learning this concept, you need to know the React fundamentals like components, state, props, and lifecycle methods. And you need to API basics like how API works, including HTTP methods like GET, POST, etc.

In react js you can fetch data in two ways which are the fetch() method and Axios() method:

Fetching Data Using fetch()

The fetch() function is a modern and built-in way to make HTTP requests in JavaScript. It returns a Promise that resolves the Response to that request. Here’s how you can use it to fetch data in a React.js component:

import React, { Component } from 'react';

class DataFetchingComponent extends Component {
  state = {
    data: null,
    loading: true,
    error: null,
  };

  componentDidMount() {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        this.setState({
          data: data,
          loading: false,
        });
      })
      .catch(error => {
        this.setState({
          loading: false,
          error: error,
        });
      });
  }

  render() {
    const { data, loading, error } = this.state;

    if (loading) {
      return <p>Loading...</p>;
    }

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

    return (
      <div>
        {/* Render data here */}
      </div>
    );
  }
}

export default DataFetchingComponent;

Using axios for Data Fetching

Another popular option for making API requests in React.js is using the axios library. axios provides a more convenient and feature-rich interface for performing HTTP requests. To use axios, follow these steps:

    1. Install the axios library using npm or yarn:
      npm install axios
    2.  Import and use axios in your React component:
      import React, { Component } from 'react';
      import axios from 'axios';
      
      class DataFetchingComponent extends Component {
        state = {
          data: null,
          loading: true,
          error: null,
        };
      
        componentDidMount() {
          axios.get('https://api.example.com/data')
            .then(response => {
              this.setState({
                data: response.data,
                loading: false,
              });
            })
            .catch(error => {
              this.setState({
                loading: false,
                error: error,
              });
            });
        }
      
        // ... render and error handling logic remains the same
      }
      
      export default DataFetchingComponent;

 

READ ALSO  How does GitHub Co-Pilot Works and Why Should we use it?

Fetching data from APIs is an essential skill for creating dynamic and interactive web applications. In this article, we explored two methods for fetching data in a React.js application: using the native fetch() function and the axios library. Both approaches offer effective ways to retrieve data and update the application’s state accordingly. By following the steps outlined in this guide, you’ll be well-equipped to integrate external data sources seamlessly into your React.js projects and create engaging user experiences.

Leave a Reply