I am using React 17.0.1. I am not able to figure out the following:
- Page re-renders if the button is clicked multiple times even when the id remains unchanged.
- Also I am encountering another error: Line 25:6: React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array react-hooks/exhaustive-deps. I am guessing this error is caused due to the fact id is set outside of the render.
import React, { useState, useEffect } from "react";
import axios from "axios";
function DataFetcing() {
const [post, setPost] = useState({});
const [id, setId] = useState(1);
const [search, setSearch] = useState(1);
const handleClick = () => {
console.log(post);
setSearch(post);
};
useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then((res) => {
console.log(res);
setPost(res.data);
})
.catch((err) => {
console.log(err);
setPost(err);
});
}, [search]);
return (
<div>
<button type="button" onClick={handleClick}>
Fetch Post
</button>
<input type="text" value={id} onChange={(e) => setId(e.target.value)} />
<span key={post.id}>{post.title}</span>
</div>
);
}
export default DataFetcing;
setPostwhich changes thepost, which in turn will be used by the nexthandleClick- Gabriele Petrioli