DEV Community

Cover image for How to Fetch Data From API in ReactJS.
Ashish maurya
Ashish maurya

Posted on • Originally published at blog.theashishmaurya.me

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.

https://gist.github.com/Ashumaurya/b48d33db8338b8d0c5edd1e61261e80c

  • 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)


https://gist.github.com/Ashumaurya/3f47d91de2b8f2358812af639e26aca9
https://gist.github.com/Ashumaurya/21196bd8f556ee69edebd72f196226d8
  • 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 fetchData in our App.js.


https://gist.github.com/Ashumaurya/75294e21d750a3fd2c9510c4a8120294
  • Now that we created the function to fetch data from the API, all we need is to call it in our App.js as soon as DOM renders.

  • We will use useEffect for fetching the data every time DOM renders.


https://gist.github.com/Ashumaurya/e160199eab4a9c03e46ebf389ae1ed2a
  • If you followed the above steps clearly you would be getting an array of Objects in your developer's console.

You would be getting something like above 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

https://codesandbox.io/embed/fetching-dummy-data-from-axios-pubbi?fontsize=14&hidenavigation=1&theme=dark

And guys do subscribe to my newsletter

This blog is posted using Blogtiple

Top comments (2)

Collapse
 
kin7777 profile image
kince marando

An eye opener

Collapse
 
gopal_sarkar_8f9f41f813d2 profile image
Gopal Sarkar

What is Hydration