cover-img

Diffrent Ways to fetch data From API in Reactjs

24 January, 2023

12

12

1

  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>
);
}
  1. 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>
);
}
  1. 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>
);
}


react

javascript

web

reactjs

beginners

development

12

12

1

react

javascript

web

reactjs

beginners

development

Kamran Ahmad
🤓💻 Software Engineer | 📝 Technical Writer | 📚 Code Enthusiast | 🤩 Always Learning ✨

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.