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
Using Worldly Wealth Wisely — Luke 16:9
Is SoFi Stock a Buy?
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
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.