Reputation: 153
I'm using react useEffect to get data from my backend, but it spams my terminal with the same message non-stop.
My code
function DataFetching() {
let [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/zoom')
.then(res => {
setPosts(res.data);
})
.catch(err => {
console.log(err)
})
})
The spam message I get on terminal
Executing (default): SELECT `id`, `subject`, `MEETINGID`, `Password`, `createdAt`, `updatedAt` FROM `data` AS `data`;```
Upvotes: 0
Views: 166
Reputation: 51946
setPosts()
is causing DataFetching
to re-render, and because your useEffect()
doesn't declare a dependencies list, it evaluates the effect after every render, so you've essentially coded an asynchronous infinite loop.
Your effect only depends on setPosts()
, so you should declare that as the only dependency. Or, recognizing that setPosts()
is already memoized by React, declare no dependencies at all:
useEffect(() => {
axios.get('http://localhost:8080/zoom').then(res => {
setPosts(res.data);
}).catch(err => {
console.log(err);
});
}, [/*setPosts*/]);
Upvotes: 2