Last active
August 29, 2020 08:43
-
-
Save abhishek2x/98dc1cec08dde6f13f67de4d00a51937 to your computer and use it in GitHub Desktop.
Using Axios with useEffect to fetch data in react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
import Axios from "axios"; | |
function DataFetching() { | |
const [post, setPost] = useState({}); | |
const [id, setId] = useState(1); | |
const [idFromButtomClick, setIdFromButtomClick] = useState(1); | |
const handleClick = () => { | |
setIdFromButtomClick(id); | |
}; | |
useEffect(() => { | |
Axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`) | |
.then((res) => { | |
console.log(res); | |
setPost(res.data); | |
}) | |
.catch((err) => { | |
console.log(err); | |
}); | |
}, [idFromButtomClick]); | |
return ( | |
<div> | |
<input type="text" value={id} onChange={(e) => setId(e.target.value)} /> | |
<br /> | |
<button type="buttton" onClick={handleClick}> | |
Fetch Post | |
</button> | |
{/* <ul> | |
{posts.map((post) => ( | |
<li key={post.id}>{post.title}</li> | |
))} | |
</ul> */} | |
{post.title} | |
</div> | |
); | |
} | |
export default DataFetching; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment