How to Fetch Data From API in ReactJS.
While developing an application in ReactJs you might be asked to fetch some data from an API directly into the frontend and then process it.
Well just fetching some data from the API is quite easy and today we gonna learn that.
Let's get started
First of all, let's create a new React app.
- Go to your terminal and copy-paste the below code.
Now open the folder in your favorite code editor. (Mine is VS code )
Let's use the
JSONPLACEHOLDER API. (It's a dummy rest API for such purposes)
Install the AXIOS library for fetching the data.
After successfully installing the AXIOS let's import it into our app.js your app.js should look something like this
Now we are almost done. All we have how to use the Axios inbuilt method
Axios.get()to fetch data from the above API.
let's get started by creating a function
Now that we created the function to fetch data from the API, all we need is to call it in our
App.jsas soon as DOM renders.
We will use useEffect for fetching the data every time DOM renders.
- If you followed the above steps clearly you would be getting an array of Objects in your developer's console.
Voila!! you have fetched the data from a rest API directly into your React App.
Next is creating a TODO APP using React-18 with the above data
here is my code sandbox link for the above application