Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 24, 2022 05:54 am

Introduction to API Calls With React and Axios


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.



1. Set Up the Project


Let's setup a React project with the create-react-app command in the terminal:



Then, open up the project directory through the terminal window and then type in npm install axios in order to install Axios for the project locally.



2. Choose a Target API


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.



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 due to the fact that 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.



3. Create the App States


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.



Here you see 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.



4. Fetch the Data With Axios


Next is to create a getUsers function that will handle fetching of the data. In this function is where 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 the useEffect and call the getUsers function inside it.


The useEffect hook basically manages the side-effects in functional components which is 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;



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:



Here we logged the name of the first value inside the results array.



5. Process the Results Data


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:



In the code above, we created a variable called the newData. It stores the results of looking through 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.







6. Populate the Data Stores With Filtering


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.



The filter method requires a function as an argument, a function to be run for each element in the array. Here we refer 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. 




7. Creating the Components


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 components to the app. First we import the components from separate JavaScript files (we'll define the files shortly):



Next we update our App component's return statement to make use of these components:



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 of the store state to show the data because the users state is the one containing the filtered results.


The SearchBar Component


This 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:



The List Component


This component will simply list the names of the users. This goes in components/List.js:



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.



7. Track The Loading State


Let's create a loading state with the useState hook to show when the data is yet to be fetched. 



Next, we'll update the loading state in our data fetch method.



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.



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, a simple loader was created to display the loading state on the interface.


8. Add Some CSS For Styling


Below you can find the CSS file specific to this example.



Conclusion


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.








Original Link: https://code.tutsplus.com/tutorials/introduction-to-api-calls-with-react-and-axios--cms-21027

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code