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 mounted. We use the axios.get
method to send a GET request to the API, and the response.data
property to retrieve the data returned by the API. We also use state variables to keep track of the loading status, error state, and data.
When the component is first rendered, the loading
state is true
, and we display a “Loading…” message. If the fetch fails, we display an error message with the error message. If the fetch succeeds, we display the data in a list.
This is a simple example, but you can use Axios in many other ways to make various types of requests and handle different types of responses. You can also configure Axios with headers, authentication, base URLs, and other settings to meet the specific needs of your application.
Sample 2
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 |
import React, { useState, useEffect, Fragment } from "react"; import axios from "axios"; const GetData = () => { const [data, setData] = useState([]); var res= axios.get('https://swapi.dev/api/planets/', { params: { // ID: 12345 } }) .then(function (response) { console.log(response); setData(response.data.results); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); console.log("res=>",res); return ( <Fragment> <h2>Call From Api :</h2> <div className="row"> {data.map(item => ( <div className="col-md-4"> <div className="card"> <div className="card-body m-2 bg-info"> <span key={item.rotation_period}>{item.name}</span> </div> </div></div> ))} </div> </Fragment> ); } export default GetData; |