Skip to content

Instantly share code, notes, and snippets.

@abhishek2x
Last active August 29, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishek2x/98dc1cec08dde6f13f67de4d00a51937 to your computer and use it in GitHub Desktop.
Save abhishek2x/98dc1cec08dde6f13f67de4d00a51937 to your computer and use it in GitHub Desktop.
Using Axios with useEffect to fetch data in react
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