简体   繁体   中英

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!!

  • I Fixed The Error Because i realised that it was an issue with Setting the state inside the child component.Thanks to everybody that invested time into Helping Me.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM