0

So I have a React.js project using Firestore, and I've noticed that when I use the get method for documents, I get the "Can't perform a React state update on an unmounted component" warning. If I use the onSnapshot method and unsubscribe it in the componentWillUnmount React method, the warning disappears, which makes sense. Why is the get method throwing this error? I don't always want to be listening for documents, so I am just wondering the best way to be going about this. Thanks!

Throws no warning:

  componentDidMount() {

      this.unsubscribeUsers = firestore.collection("users").doc(this.props.user.uid).onSnapshot((doc) => {
        this.setState({
          firstName: doc.data().firstName,
        })
      });
  }

  componentWillUnmount() {
    if(this.unsubscribeUsers){
      this.unsubscribeUsers();
    }
  }

Throws warning:

  componentDidMount() {
      firestore.collection("users").doc(this.props.user.uid).get().then((doc) => {
        if (doc.exists) {
          this.setState({
            firstName: doc.data().firstName,
          })
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
      }).catch(function(error) {
          console.log("Error getting document:", error);
      });
  }

Full error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
douglasrcjames
  • 1,133
  • 3
  • 17
  • 37
  • Did you find the solution? I am also getting same issue in get() method. I wonder if there is any unsubsribe method for get() – MSM Jun 15 '22 at 15:11

1 Answers1

0

This seems to be on how both methods works. As explained in this answer, the get() method takes the data only once while the onSnapshot() continues listening on the doc. The warning is related that you will not have updates on the component (the doc) because how get() works.

Puteri
  • 3,348
  • 4
  • 12
  • 27