- Report this article
Khaled Bellal 🦊
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.
Like
Celebrate
Support
Love
Insightful
Funny
37
5 Comments
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.
1Reaction
Firoz Khan
Front-End Developer
12mo
- Report this comment
please do use screenshot of result also.
No more previous content
No more next content
1Reaction
Austin Ameh
1y
- Report this comment
Great content. Got the concept in clear details
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
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
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
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