Different Ways to fetch data from API in Reactjs

Different Ways to fetch data from API in Reactjs

Table of contents

No heading

No headings in the article.

  1. Using the fetch() method:

     import React, { useState, useEffect } from 'react';
    
     function Example() {
       const [data, setData] = useState([]);
    
       useEffect(() => {
         fetch('https://api.example.com/data')
           .then(response => response.json())
           .then(data => setData(data))
       }, []);
    
       return (
         <div>
           {data.map(item => (
             <div key={item.id}>{item.name}</div>
           ))}
         </div>
       );
     }
    
  2. Using the axios library:

     import React, { useState, useEffect } from 'react';
     import axios from 'axios';
    
     function Example() {
       const [data, setData] = useState([]);
    
       useEffect(() => {
         axios.get('https://api.example.com/data')
           .then(response => setData(response.data))
       }, []);
    
       return (
         <div>
           {data.map(item => (
             <div key={item.id}>{item.name}</div>
           ))}
         </div>
       );
     }
    
  3. Using the async/await syntax:

     import React, { useState, useEffect } from 'react';
     import axios from 'axios';
    
     function Example() {
       const [data, setData] = useState([]);
    
       useEffect(() => {
         async function fetchData() {
           const response = await axios.get('https://api.example.com/data');
           setData(response.data);
         }
         fetchData();
       }, []);
    
       return (
         <div>
           {data.map(item => (
             <div key={item.id}>{item.name}</div>
           ))}
         </div>
       );
     }
    
  4. Using the swr library:

     import React, { useState } from 'react';
     import useSWR from 'swr';
    
     function Example() {
       const { data, error } = useSWR('https://api.example.com/data');
    
       if (error) return <div>Failed to load data</div>;
       if (!data) return <div>Loading...</div>;
    
       return (
         <div>
           {data.map(item => (
             <div key={item.id}>{item.name}</div>
           ))}
         </div>
       );
     }