Fetching Data with Axios in React (2024)

Fetching Data with Axios in React (1)

  • Report this article

Khaled Bellal 🦊 Fetching Data with Axios in React (2)

Khaled Bellal 🦊

Electronic / Front-End Developer & Graphic Designer React.js || JavaScript || TypeScript || TailwindCSS || Design || Photoshop

Published Apr 7, 2023

+ Follow

Axios is a popular JavaScript library used for making HTTP requests, and it can be especially useful in React applications for fetching data from APIs. In this blog post, we'll explore how to use Axios in a React application to fetch data from an API and display it on the page.
import { useEffect, useState } from "react"import axios from "axios";interface User { id: number; name: string}function App() { const [users, setUsers] = useState<User[]>([]); const [error, setError] = useState(''); useEffect(() => { axios .get<User[]>("https://jsonplaceholder.typicode.com/users") .then((res) => setUsers(res.data)) .catch(err => { setError(err.message); }); }, []); return ( <> {error && <p className="text-danger">{error}</p>} <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> </> ); } export default App; 

The code above demonstrates how to use Axios in a React component to fetch a list of users from the JSONPlaceholder API and display them in a list. Let's go through each part of the code step-by-step:

Importing Dependencies:

The code imports two dependencies - `useEffect` and `useState` from the React library and `axios` library.
import { useEffect, useState } from "reactimport axios from "axios";" 

Defining User Interface:

An interface named `User` is defined with two properties `id` and `name`.
interface User { id: number; name: string} 

Defining the Component:

The `App` function is defined which is the main component in this code. It uses `useState` hook to declare `users` state which is initially set to an empty array.
 const [users, setUsers] = useState<User[]>([]); 

useEffect Hook:

The `useEffect` hook is used to make an HTTP GET request to the JSONPlaceholder API to retrieve a list of users. When the component mounts, the `useEffect` hook is triggered and makes an API call using the `axios.get()` method. The API endpoint is passed as an argument to the method. The `axios.get()` method returns a promise which resolves with the response data.
 useEffect(() => { axios .get<User[]>("https://jsonplaceholder.typicode.com/users") .then((res) => setUsers(res.data)) .catch(err => { setError(err.message); }); }, []) 

Updating state with Response Data:

The `then` method is chained to the promise, which updates the `users` state with the response data by calling the `setUsers` function. The `catch` method is also chained to the promise to handle errors and log them to the console.

Displaying User Data:

The overall purpose of this code is to render a list of users' names within an unordered list (<ul>) element. If there is an error present, it will also display an error message above the list. This is a common pattern in React components for displaying dynamic data fetched from an API, where the list is generated based on the data received.
return ( <> {error && <p className="text-danger">{error}</p>} <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> </> ); 
By using the `axios.get()` method to fetch data from an API and updating the state with the response data, we can easily display the fetched data in our React components.
In conclusion, using Axios with React is a powerful combination for making HTTP requests and fetching data from APIs. By understanding the code above, you can apply these concepts to your own React projects and make use of the vast amount of data available on the internet.

william NYARANGA

Computer scientist | web developer| Artist| graphic Designer| and other stuff

10mo

  • Report this comment

So I am doing a course in react and I was stuck on manipulating data from the an API but your article was a life saver. It gave me more insight on how to use axios and so much more.Thank you Khaled Bellal 🦊 and I hope that you will continue to publish more content like this one.

Like Reply

1Reaction

Firoz Khan

Front-End Developer

12mo

  • Report this comment

please do use screenshot of result also.

  • Fetching Data with Axios in React (14)

No more previous content

  • Fetching Data with Axios in React (15)

No more next content

Like Reply

1Reaction

Austin Ameh

1y

  • Report this comment

Great content. Got the concept in clear details

Like Reply

1Reaction

Abd Elsalam Salem

Accountant | Accounting behind screen | ERP | I help company to achieving the goals with strategy |

1y

  • Report this comment

Thanks for sharing

Like Reply

1Reaction 2Reactions

HulkHire

1y

  • Report this comment

Hello Khaled...We post 100's of job opportunities for developers daily here.Candidates can talk to HRs directly. Feel free to share it with your network.Visit this link - https://jobs.hulkhire.com And start applying..Will be happy to address your concerns, if any

Like Reply

1Reaction 2Reactions

See more comments

To view or add a comment, sign in

More articles by this author

No more previous content

  • Understanding the Power of useEffect in React.js: A Comprehensive Guide Apr 5, 2023
  • Why Learning Next.js is Essential for Modern Web Development Apr 2, 2023
  • Getting Started with Next.js: A Beginner's Guide Apr 1, 2023
  • Building a form in React with TypeScript Mar 31, 2023

No more next content

See all

Sign in

Stay updated on your professional world

Sign in

By clicking Continue to join or sign in, you agree to LinkedIn’s User Agreement, Privacy Policy, and Cookie Policy.

New to LinkedIn? Join now

Insights from the community

  • Software Design What are the benefits of using KnockoutJS with Backbone.js for data binding?
  • Quality Assurance What are the best practices for optimizing web applications across different date and time currency formats?
  • Web Development How can you debug a website that is displaying incorrect data?
  • HTML5 What are the benefits and drawbacks of using jQuery to manipulate custom data attributes?
  • Web Applications How can you implement data binding in your JavaScript library?
  • Web Development How can you use APIs to integrate external data?
  • Representational State Transfer (REST) What are the most popular REST API frameworks?
  • Internet Services What internet service technologies should you learn?
  • Web Applications How do you connect web apps to other systems?
  • Middleware How do you choose between async and sync middleware for your web app?

Others also viewed

  • State Management in React - Part 3 of “Learning React as a Frontend Developer with 3.5 Years of Vue Experience” Ahmet Otenkaya 1mo
  • Promises 101 and Fetch, Axios and $.ajax Alex Merced 4y
  • The React Dev's Balancing Act: Harmonizing Diverse Technologies Andre Liem 5mo
  • JavaScript with Node.js Khuram Mohammad . 1y
  • JavaScript Data Types Mansoor Ahmed 2y
  • 🌐 Mastering JavaScript Web APIs: Unlocking the Power of Browser Features! 🌐 JavaScript Developer Freelancer 6mo
  • Vue js : Its Component and API Bitwork Labs 1y
  • Build an ORDS API Resource Module, GET request with JavaScript fetch, display in HTML Chris Hoina 5mo
  • Create your own COVID tracker using node.js, npm, express, ejs and bootstrap Arul Benjamin Chandru Ebenezer Vedanayagam 3y
  • Collect Reasons to Learn AngularJS Malini Shukla 5y

Explore topics

  • Sales
  • Marketing
  • IT Services
  • Business Administration
  • HR Management
  • Engineering
  • Soft Skills
  • See All
Fetching Data with Axios in React (2024)
Top Articles
CONTRACT: Critical success factors for contracting - OSTKv1-0
Skydiving: Why It’s Different Than What You Think - Skydive Orange
Whas Golf Card
Nybe Business Id
Georgia Vehicle Registration Fees Calculator
Sam's Club Gas Price Hilliard
EY – все про компанію - Happy Monday
Gw2 Legendary Amulet
Bhad Bhabie Shares Footage Of Her Child's Father Beating Her Up, Wants Him To 'Get Help'
Vocabulario A Level 2 Pp 36 40 Answers Key
Select Truck Greensboro
South Bend Tribune Online
Readyset Ochsner.org
The most iconic acting lineages in cinema history
Best Suv In 2010
Niche Crime Rate
Craighead County Sheriff's Department
Weather Rotterdam - Detailed bulletin - Free 15-day Marine forecasts - METEO CONSULT MARINE
Odfl4Us Driver Login
UMvC3 OTT: Welcome to 2013!
How to Make Ghee - How We Flourish
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
1145 Barnett Drive
Tire Plus Hunters Creek
Craigslist Ludington Michigan
Craigslist Rome Ny
Skymovieshd.ib
Access a Shared Resource | Computing for Arts + Sciences
Pioneer Library Overdrive
Miles City Montana Craigslist
Tu Housing Portal
Ringcentral Background
Mrstryst
Egg Crutch Glove Envelope
Robot or human?
20 Best Things to Do in Thousand Oaks, CA - Travel Lens
5 Tips To Throw A Fun Halloween Party For Adults
Dee Dee Blanchard Crime Scene Photos
Gold Dipping Vat Terraria
Nba Props Covers
Gravel Racing
Gasoline Prices At Sam's Club
Setx Sports
Brown launches digital hub to expand community, career exploration for students, alumni
Kate Spade Outlet Altoona
UNC Charlotte Admission Requirements
Clock Batteries Perhaps Crossword Clue
Cars & Trucks near Old Forge, PA - craigslist
Kobe Express Bayside Lakes Photos
Emmi-Sellers
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6102

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.