How to fetch data from third party API in Reactjs
In this demo, I am going to create a React app in which we will fetch data from third party API. We will use here create-react-app command line tool here to create our react demo. And for this I assume that Node.js and npm is already installed in your system, If its not installed please install these first to start working with this demo.
Lets proceed step by step:
Step 1: create react app
create a react app with create-react-app command line tool, So create app and run the created app with the below commands:
After complete execution of above command you will be able to see a basic react app over browser having url http://localhost:3000. Now basic app is created successfully in your application.
Step 2: Create separate component
In the above file we have simply imported the react library at the top. Below that created a class which is extending Component for react library, Inside that class there some dummy html content to render for now. Now if want to reflect the content of this component then we need to change the content of the src/App.js file and put the below code inside return
Listing is imported at the top of the file with command import Listing from './listing/Listing'. Now we can see the content at browser over the link http://localhost:3000 has changed with showing only Listing data text.
Step 3: Fetch data from third party api:
At first we will initialize the variables inside the constructor funciton of Listing component by adding below lines.
Now we will write code for fetching data from third party API, Let's have look on code which is fetching data from server:
In the above code we can see, that setState method is being used for response of fetch API. And after fetching the data from the API it will update the state of the listing component. After that rending code of the app will show to our browser over the http://localhost:3000/
Step 4: render the data over the browser:
In this section we are performing the very basic task of showing the data loaded in the records variable after iterating it. Let's have a look on the code:
In the above code, we can see there is a function renderListing, in which we are iterating the data array and pushing it into recordList array. Now the fetched data will show over browser.
That’s all for now. Thank you for reading and I hope this post will be very helpful for implementation of fetching data from third party API in reactjs application.
Let me know your thoughts over the email firstname.lastname@example.org. I would love to hear them and If you like this article, share with your friends.
You can download complete code from here. Download Code