I just started studying React Hooks so I'm kind of a newbie here.
I'm struggling to find out why the below code falls into an infinite loop.
I can't find any problems with a code.
Is there anyone who could sort out this problem?
import React, { useEffect, useState } from "react";
import axios from "axios";
export interface Post {
userId: number;
id: number;
title: string;
body: string;
}
function PostFetchingOne() {
const [id, setId] = useState(1);
const [post, setPost] = useState<Partial<Post>>({});
useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then((res) => {
setPost(res.data);
console.log("post => ", post);
})
.catch((err) => {
console.log(err);
});
}, [id, post]);
return (
<>
<div>
<input
type="text"
onChange={(e) => setId(+e.target.value)}
value={id}
/>
</div>
<div>{post.title}</div>
</>
);
}
export default PostFetchingOne;
postfrom dependencies.idis a correct dependency,postis not. If you want toconsole.logyourpoststate that should be in a dedicateduseEffectand that will certainly havepostas a dependency:useEffect(() => { console.log('post => ', post); }, [post]);