PostList Component when I am adding the createCFommonent then I am getting the too many re-render Error. React limits the number of renders to prevent an infinite loop.
import React,{useState,useEffect} from 'react';
import axios from 'axios'
import './PostList.css'
import CommentCreate from './CommentCreate';
const PostList = () => {
const [ptitle,setPtitle]=useState({});
const fetchPost = async ()=> {
const res=await axios.get('http://localhost:8000/posts')
setPtitle(res.data)
}
useEffect(() => {
fetchPost()
}, [])
const renderedPost = Object.values(ptitle).map((post) => {
return (
<div
className="card"
style={{ width: "30%", marginBottom: "20px" }}
key={post.id}
>
<div className="card-body">
<h3>{post.title}</h3>
<CommentCreate postId={post.id} />
</div>
</div>
);
});
return (
<div>
<h1>Post List</h1>
{renderedPost}
</div>
);
}
export default PostList;
createComment Component this is the Component which is giving Consider adding an error boundary to your tree to customize error handling behavior.
import React,{useState} from 'react';
import axios from 'axios'
import './CommentCreate.css'
const CommentCreate = ({postId}) => {
const [comment, setComment]=useState('')
const createComment = async (e) =>{
e.preventDefault();
await axios.post(`http://localhost:9000/post/${postId}/comment`, {
comment,
});
}
setComment('')
return (
<div>
<input value={comment} onChange={e =>{
setComment(e.target.value)
}} placeholder="Create a Comment here" />
<button class="btn btn-primary" onClick={createComment}>
Comment
</button>
</div>
);
}
export default CommentCreate;
```
PROBLEM
You
createComment
gets updated by parent andsetComment
is called which triggers a re-render again callingsetComment
. Thus an infinite re-render.SOLUTION
Place your
setComment
inside thecreateComment
function.