Why am I getting infinite loop error? React refers to the line marked with *
:
function Blog() {
const [blog, setBlog] = useState({});
const query = useQuery();
async function takeBlog(query) {
const _data = await (await fetch(`${root}/api/blog/${query}`)).json();
console.log(_data.blog)
setBlog(_.get(_data, 'blog', {})); // *
}
useEffect(() => {
takeBlog(query);
}, []);
return (
<div className="blog_page">
<div className="container">
<div className="top">
</div>
<div className="other ab">
<div className="left">
<Navbar active='blogs' />
</div>
<div className="right">
<Posts posts={_.get(blog, 'articles', [])} />
</div>
</div>
</div>
</div>
);
}
Top comments (2)
You could try moving takeBlog() inside the useEffect
useEffect(() => {
async function takeBlog(query) {
const data = await (await fetch(
${root}/api/blog/${query}
)).json();console.log(_data.blog)
setBlog(.get(_data, 'blog', {})); // *
}
takeBlog(query);
}, []);
This shouldn't be an issue due to the dependancy array being empty but could be worth trying.
I'd also change the setBlog line as I'm not sure what effect lodash will have in setState. I'd do something like
const articles =_.get(_data, 'blog.articles', {});
setBlog(articles)
and of course change what you pass to Posts. Hope this helps
stackoverflow.com/questions/533323...
use react-query and you won't have that problem:
react-query.tanstack.com/