1

just starting to learn hooks here.

I am getting data from firestore and trying to set it to state using hooks. when I uncomment the line doing so, I get stuck in an infinite loop. no error, but the console goes crazy with logging the state thousands of times.

Let me know if you need more info!

function Lists(props) {

    const [lists, setLists] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const subscriber = 
            firestore().collection('users').doc(props.user).collection('lists')
              .onSnapshot(QuerySnapshot => {
                  const items = []
                  QuerySnapshot.forEach(documentSnapshot => {
                      items.push({
                          ...documentSnapshot.data(),
                          key: documentSnapshot.id,
                      });
                    //setLists(items)

                    setLoading(false)

                    console.log(lists)
                  })

            })
            // unsubscribe from firestore
            return () => subscriber();
    })

//rest of func..
TrevPennington
  • 435
  • 5
  • 15

1 Answers1

2

this issue happens becauase useEffect gets called over and over again. useEffect is like componentDidMount and componentDidUpdate if you are familiar with React class components.

so whenever you set the state inside the useEffect, you trigger an update, and then, useEffect gets called again, and thus the infinite loop.

to fix this, useEffect accepts a extra argument, which is an array of dependancies, which indicates that this useEffect call should only re-executed whenever a change happens to one of its dependancies. in your case you can provide an empty array, telling react that this useEffect should only be called one time.

 useEffect(() => {
        const subscriber = 
            firestore().collection('users').doc(props.user).collection('lists')
              .onSnapshot(QuerySnapshot => {
                  const items = []
                  QuerySnapshot.forEach(documentSnapshot => {
                      items.push({
                          ...documentSnapshot.data(),
                          key: documentSnapshot.id,
                      });
                    //setLists(items)

                    setLoading(false)

                    console.log(lists)
                  })

            })
            // unsubscribe from firestore
            return () => subscriber();
    }, []) // <------------ the second argument we talked about
Ahmed Khattab
  • 2,645
  • 2
  • 13
  • 19