Adityan.P
Adityan.P

Reputation: 112

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. React

I am Facing the Below Mentioned Error When Fetching Data from Firebase and Setting it to State Inside a useEffect Hook.

Here is The Code i am Using With Simplified Markup:

function PostComponent({ id }){
  const [post,setPost] = useState({});
  const [error,setError] = useState("");

  const db = firebase.firestore();

  useEffect(()=>{
    db.collection('posts').doc(id).get().then(doc=>{
      setPost(doc.data());
    }).catch(err=>setError(err.message));
  }, []);

  return (
    {error && <h1>{ error }</h1>}
    <PostCard data={post} />
  );
}

Update!!

Upvotes: 0

Views: 213

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

Can you pls try it like this:


//this can be outsite of your component
const db = firebase.firestore();

function PostComponent({ id }){
  const [post,setPost] = useState({});
  const [error,setError] = useState("");

  useEffect(()=>{
    db.collection('posts').doc(id).get().then(doc=>{
      setPost(doc.data());
    }).catch(err=>setError(err.message));
  }, [id]);

  return (
    {error && <h1>{ error }</h1>}
    <PostCard data={post} />
  );
}

If that doesn't work then the error is probably comming from another component.

Upvotes: 2

Related Questions