Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, How to fetch api data in reactjs using useState useEffect hook?
For reactjs new comers, please check the below link:
Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:
1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system and bootstrap as well:
npx create-react-app reactdemo cd reactdemo npm install bootstrap npm i @popperjs/core npm start
2. Finally for the main output, we need to add below code into our reactdemo/src/App.js file or if you have fresh setup then you can replace reactdemo/src/App.js file code with below code:
// 1. Import *useState* and *useEffect* import React, {useState, useEffect} from 'react'; import "bootstrap/dist/css/bootstrap.min.css" function App() { // 2. Create our *data* variable as well as the *setdata* function via useState // We're setting the default value of data to null, so that while we wait for the // fetch to complete, we dont attempt to render the data let [data, setdata] = useState(null) // 3. Create out useEffect function useEffect(() => { fetch("https://therichpost.com/testjsonapi/users/") .then(response => response.json()) // 4. Setting *data* to the API DATA that we received from the response above .then(data => setdata(data)) },[]) return ( <div className="App container py-5"> <table class="table"> <thead> <tr> <th scope="col">#ID</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Job Title</th> </tr> </thead> <tbody> {data && (data.map(item => <tr> <th scope="row">{ item.id }</th> <td>{ item.name }</td> <td>{ item.email }</td> <td>{ item.job_title }</td> </tr> ))} </tbody> </table> </div> ); } export default App;
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks
Recent Comments