Diffrent Ways to fetch data From API in Reactjs
24 January, 2023
12
12
1
Contributors
- 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>
);
}
- 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>
);
}
- 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