react fetchapi
//use effect is a replacement of componentDidMount,ComponentDidUpdate and ComponentWillUnmount
.........................................................................
Fetching data with React hooks and Axios - DEV Community
import React ,{useState,useEffect} from 'react'
export default function H4() {
const [post,setposts]=useState([]);
useEffect( ()=>{
// API for get requests
let fetchRes = fetch(
"https://jsonplaceholder.typicode.com/posts");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then(res =>
res.json()).then(d => {
setposts(d)
console.log(d)
})},[])
return (
<div>
{post.map((e,index)=><li key={index}>{e.id}{e.title}</li>)}
</div>
)
}
//.............................................................................
//useeffect with two parameter first is the function we are passing into it and the second one
is the dependency array that allows the hook to render once.
import React,{useState,useEffect} from 'react'
import axios from 'axios'
function Fetch_api_useEffect() {
const [posts, setPosts] = useState([]);
useEffect(()=>{
axios.get('https://jsonplaceholder.typicode.com/posts').then(res=>{
console.log(res)
setPosts(res.data)
}).catch(err=>console.log(err))
},[])
return (
<div>
<ul>
{posts.map((element)=>(
<li key={element.id}>{element.id}{element.title}</li>
))}
</ul>
</div>
)
}
export default Fetch_api_useEffect
https://javascript.works-hub.com/learn/how-to-fetch-data-from-an-api-using-react-hooks-54d70
Comments
Post a Comment