use axios in react with sample
Axios is a popular library for making HTTP requests in JavaScript, and it’s often used in React projects to retrieve data from APIs and other server-side resources. Here’s an example of how you can use Axios in a React component to fetch data from a server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const Example = () => { const [data, setData] = useState([]); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { setLoading(true); setError(null); try { const response = await axios.get('https://api.example.com/data'); setData(response.data); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, []); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <ul> {data.map(item => ( <li key={item.id}>{item.title}</li> ))} </ul> ); }; export default Example; |
In this example, we use the useEffect hook to fetch data from an API when the component is… ادامه »use axios in react with sample