Table of contents
No headings in the article.
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> ); }
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> ); }