How to useaxios library in ReactJS
Axios is a Promise based JavaScript Library use to make the http request from the browser. We will use axios.get method to fetch the data from the given api and then present it on the web pages as required using react jsx components.
Steps to install axios:
npm i axios
Example: This example uses axios to get the data from the api and represent on the web page.
Javascript
// App.js import React from "react" ; import "./App.css" ; import axios from "axios" ; // uimport axios class App extends React.Component { // Constructor constructor(props) { super (props); this .state = { items: [], DataisLoaded: false , }; } // ComponentDidMount is used to // execute the code componentDidMount() { axios.get( "https://jsonplaceholder.typicode.com/users" ) .then((res) => { this .setState({ items: res.data, DataisLoaded: true , }); }); } render() { const { DataisLoaded, items } = this .state; if (!DataisLoaded) return ( <div> <h1> Pleses wait some time.... </h1> </div> ); return ( <div className= "App" > <h1 className= "geeks" >w3wiki</h1> <h3>Fetch data from an api in react</h3> <div className= "container" > {items.map((item) => ( <div className= "item" > <ol key={item.id}> <div> <strong> { "User_Name: " } </strong> {item.username}, </div> <div> Full_Name: {item.name}, </div> <div> User_Email: {item.email} </div> </ol> </div> ))} </div> </div> ); } } export default App; |
CSS
/* App.css*/ .App { text-align : center ; /* color: Green; */ } .container { display : flex; flex- direction : row; flex-wrap: wrap; justify- content : center ; } .item { min-width : 33 rem; text-align : left ; } .geeks { color : green ; } |
Steps to run the application:
npm start
Output: This output will be visible on http://localhost:3000/
How to fetch data from an API in ReactJS ?
Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. It can be done by using the methods listed below.
Table of Content
- Using JavaScript fetch method
- Using axios library
Steps to create the React application:
Step 1: Create React Project
npm create-react-app myreactapp
Step 2: Change your directory and enter your main folder charting as
cd myreactapp
Step 3: Write code in App.js to fetch data from API and we are using the fetch function.