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.