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;

```
2

There are 2 answers

0
Prateek Thapa On

PROBLEM

You createComment gets updated by parent and setComment is called which triggers a re-render again calling setComment. Thus an infinite re-render.

SOLUTION

Place your setComment inside the createComment function.

  const createComment = async (e) =>{
        e.preventDefault();
        await axios.post(`http://localhost:9000/post/${postId}/comment`, {
          comment,
        });
        
        setComment('')
    }

0
Piyush Rana On

You are setting state globally setComment(''). Consider using useEffect if you wanna set state only when component mounts. Use the below snippets:

useEffect(() => setComment(''), []);

Setting state globally will cause component to re-render and again on re-rendering setComment('') will called, this procedure follows indefinitely and you'll getting the infinte loop error which you are. So my suggestion is never set state without using useEffect or without meeting any specific condition.