This article will show how to get/fetch data from api using axios in useEffect and save it to usestate and show that data on the webpage in table format.
Here I will explain every line of code in details so take a minute and read it fully for better understanding and if you stuck in any problem then feel free to contact me in any social media.
- Axios to fetch data from api
- UseEffect to tell react that the component is needs to do after render
- UseState to set state variable and state function and it allows us to add state to functional components.
Import axios and make a GET request
Use npm i axios to install axios and then add it as an import import axios from 'axios' to your parent component. I’m going to use axios to get all of my data from , which I stored in a database.
In default function in app.js
At above code i will explain every line of code in details here
useState used to state alteration
const means constant which is datatype
databs is variable here which used to store our api data
setdatabs is state function which help to get data from the api and set it to databs
useEffect runs only once i.e. the code inside useEffect will only get executed once even if we change the value of the variable count multiple times.
and here useEffect(()=>{…} is known as fat arrow.
axios.get("https://jsonplaceholder.typicode.com/posts")
axios used to fetch data using the get(http request method) method from API
"https://jsonplaceholder.typicode.com/posts"
URL of the api
.then((res)
now we have to check that if Api working successfully or not so first
.then(res) used here will check if its successful and res is just a user defined variable
setdatabs(res.data)
setdatabs is state function and we want to tell the function that data is fetching and
what to do with that data so we give that data i.e. res.data to state function which will transfer this data to data state variable.
Now Api hit and data come but we know that data came but how user will know and obviously
want to see that data so let's create a simple html table to show data in proper manner.