This tutorial will teach you how to use Axios to fetch data and then how to manipulate it and eventually display it on your page with filtering functionality. You will learn how to use the map, filter and includes methods along the way. On top of that, you will be creating a simple loader to handle the loading state of the fetched data from the API endpoint.
Let's set up a React project with the create-react-app
command in the terminal:
npx create-react-app project-name
Then, open up the project directory through the terminal window and type in npm install axios
to install Axios for the project locally.
We will be using the Random User Generator API to fetch random user information to use in our application.
Let's add the Axios module to our application by importing it into our App.js
file.
import axios from 'axios'
The Random User Generator API offers a bunch of options for creating various types of data. You can check the documentation for further information, but for this tutorial, we will keep it simple.
We want to fetch ten different users, and we only need the first name, last name, and a unique ID, which is required for React when creating lists of elements. Also, to make the call a bit more specific, let's include the nationality option as an example.
Below is the API URL that we will make a call for:
https://randomuser.me/api/?results=10&inc=name,registered&nat=fr
Note that I didn't use the id
option provided in the API because it sometimes returns null
for some users. So, just to make sure that there will be a unique value for each user, I included the registered
option in the API.
You can copy and paste it into your browser, and you will see the returned data in JSON format.
Now, the next thing is to make an API call through Axios.
First of all, let's create states using the useState
hook from React so that we can store the fetched data.
Inside our App
component, import the useState
hook from React and then create the states as shown below.
import React, { useState } from "react"; import axios from "axios"; const App = () => { const [users, setUsers] = useState([]); const [store, setStore] = useState([]); return ( <div> </div> ); }; export default App;
Here you can see the users
and store
states. One will be used for filtering purposes and will not be edited, and the other one will hold the filter results that will be shown in the DOM.
The next we need to do is create a getUsers
function that will handle the fetching of the data. In this function, we use axios
to fetch our data from the API using the get
method.
Now, in order to display our fetched data when the page loads, we will import a React hook called useEffect
and call the getUsers
function inside it.
The useEffect
hook basically manages the side effects in functional components, and it's similar to the componentDidMount()
lifecycle hook used in React class-based components. This hook accepts an empty array as a second argument for the purpose of side-effect cleanups.
Update the code in the App
component as shown below so we can check for our response data in the console.
import React, { useState, useEffect } from "react"; const App = () => { const [users, setUsers] = useState([]); const [store, setStore] = useState([]); const getUsers = () => { axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then(response => console.log(response)) }; useEffect(() => { getUsers(); }, []); return ( <div> </div> ); }; export default App;
When you check the console, you will see an object output. If you open up this object, there is another object inside it named data
, and inside data, there is an array named results
.
If we wanted to return a specific value from the results, we could update the axios.get
call as follows:
axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then(response => console.log(response.data.results[0].name.first))
Here we logged the name of the first value inside the results array.
Now let's use the built-in map
method of JavaScript in order to iterate through each element inside the array and create a new array of JavaScript Objects with a new structure.
Update your getUsers
function with the following code:
const getUsers = () => { axios .get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then((response) => { const newData = response.data.results.map((result) => ({ name: `${result.name.first} ${result.name.last}`, id: result.registered })); setUsers(newData); setStore(newData); }) .catch((error) => { console.log(error); }); };
In the code above, we created a variable called newData
. It stores the results of looking through the response.data.results
array with the map
method. Within the map
callback, we referenced each element of the array as result
(notice the singular/plural difference). Also, by using the key-value pair of each object inside the array, we created another object with name
and id
key-value pairs.
Ordinarily, If you check the result of the API call in your browser, you will see that there are first
and last
key-value pairs inside the name
object, but no key-value pair for a full name. So, from the code above, we were able to combine the first
and last
names to create a full name inside a new JavaScript object. Note that JSON and JavaScript objects are different things, although they basically work the same way.
Then we set the new intermediate data to the setUsers
and setStore
states.
The idea of filtering is quite simple. We have our store
state, and it always keeps the original data without changing. Then, by using the filter
function on this state, we only get the matching elements and then assign them to the users
state.
const filteredData = store.filter((item) => ( item.name.toLowerCase().includes(event.target.value.toLowerCase()))
The filter
method requires a function as an argument, a function to be run for each element in the array. Here we refer to each element inside the array as item
. Then we take the name
key of each item
and convert it to lower case in order to make our filtering functionality case insensitive.
After we have the name
key for the item
, we check if this one includes the search string we typed in. includes
is another built-in JavaScript method. We pass the search string typed in the input field as an argument to includes
, and it returns if this string is included in the variable it was called on. Again, we convert the input string to lower case so that it does not matter whether you type upper or lower case inputs.
In the end, the filter
method returns the matching elements. So we simply take these elements and store them in the setUsers
state.
Update the App
component with the final version of the function we created.
const filterNames = (event) => { const filteredData = store.filter((item) => item.name.toLowerCase().includes(event.target.value.toLowerCase()) ); setUsers(filteredData); };
Although for this small example we could put everything inside the App
component, let's take advantage of React and make some small functional components.
Let's add a couple of components to the app. First, we import the components from separate JavaScript files (we'll define the files shortly):
import Lists from "./components/Lists"; import SearchBar from "./components/SearchBar";
Next, we update our App component's return
statement to make use of these components:
return ( <div className="Card"> <div className="header">NAME LIST</div> <SearchBar searchFunction={filterNames} /> <Lists usernames={users} /> </div> );
For the time being, we will be just focusing on the functionality. Later, I will provide the CSS file I have created.
Notice that we have the searchFunction
prop for the SearchBar
component and the usernames
prop for the Lists
component.
Note also that we use the users
state instead the store
state to show the data because the users
state is the one containing the filtered results.
SearchBar
ComponentThis component is quite straightforward. It only takes the filterNames
function as a prop and calls this function when the input field changes. Put the following code in components/SearchBar.js:
import React from 'react'; const SearchBar = ({ searchFunction}) => { return ( <div> <input className="searchBar" type='search' onChange={searchFunction} /> </div> ) }; export default SearchBar;
This component will simply list the names of the users. This goes in components/List.js:
import React from 'react'; const Lists = ({ usernames }) => { return ( <div> <ul> {usernames.map(username => ( <li key={username.id}>{username.name}</li> ))} </ul> </div> ) }; export default Lists;
Here, we again used the map
method to get each item in the array and create a <li>
item out of it. Note that when you use map
to create a list of items, you need to use a key
in order for React to keep track of each list item.
Let's create a loading state with the useState
hook to show when the data is yet to be fetched.
const [loading, setLoading] = useState(false);
Next, we'll update the loading state in our data fetch method.
const getUsers = () => { axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then((response) => { const newData = response.data.results.map((result) => ({ name: `${result.name.first} ${result.name.first}`, id: result.registered, })); setLoading(true); setUsers(newData); setStore(newData); }) .catch((error) => { console.log(error); }); };
Here, we created a loading
state and set it to false initially. Then we set this state to true while fetching the data with the setLoading
state.
Finally, we'll update our return statement to render the loading state.
return ( <> {loading ? ( <div className="Card"> <div className="header">NAME LIST</div> <SearchBar searchFunction={filterNames} /> <Lists users={users} /> </div> ) : ( <div className="loader"></div> )} </> );
Using the JavaScript ternary operator, we conditionally rendered the SearchBar
and Lists
components when the loading state is false and then rendered a loader when the loading state is true. Also, we created a simple loader to display the loading state in the interface.
Below you can find the CSS file specific to this example.
body, html { -webkit-font-smoothing: antialiased; margin: 0; padding: 0; font-family: "Raleway", sans-serif; -webkit-text-size-adjust: 100%; } body { display: flex; justify-content: center; font-size: 1rem/16; margin-top: 50px; } li, ul { list-style: none; margin: 0; padding: 0; } ul { margin-top: 10px; } li { font-size: 0.8rem; margin-bottom: 8px; text-align: center; color: #959595; } li:last-of-type { margin-bottom: 50px; } .Card { font-size: 1.5rem; font-weight: bold; display: flex; flex-direction: column; align-items: center; width: 200px; border-radius: 10px; background-color: white; box-shadow: 0 5px 3px 0 #ebebeb; } .header { position: relative; font-size: 20px; margin: 12px 0; color: #575757; } .header::after { content: ""; position: absolute; left: -50%; bottom: -10px; width: 200%; height: 1px; background-color: #f1f1f1; } .searchBar { text-align: center; margin: 5px 0; border: 1px solid #c4c4c4; height: 20px; color: #575757; border-radius: 3px; } .searchBar:focus { outline-width: 0; } .searchBar::placeholder { color: #dadada; } .loader { border: 15px solid #ccc; border-top: 15px solid #add8e6; border-bottom: 15px solid #add8e6; border-radius: 50%; width: 80px; height: 80px; animation: rotate 2s linear infinite; } @keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
Throughout this tutorial, we used the Random User Generator API as a source of random data. Then we fetched the data from an API endpoint and restructured the results inside a new JavaScript object with the map
method.
The next thing was to create a filtering function with the filter
and includes
methods. Finally, we created two different components and conditionally rendered our components with a loading state when the data is not fetched yet.
Over the last couple of years, React has grown in popularity. In fact, we have a number of items in Envato Market that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…