8

okay so I'm fetching data from Firestore in componentDidMount but while it's fetching the data if I change the component I get error saying:

Warning: Can't call setState (or forceUpdate) 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.

In Firebase real time database we call ref.off() to stop query.

Wondering how to do it in Firestore

componentDidMount() {
  Users.get().then(({ docs }) => {
    const users = docs.map(user => user.data());
      this.setState({ users });
  });
}

componentWillUnmount(){

}
Jeff Adam
  • 103
  • 1
  • 11
Muhammad Ovi
  • 1,053
  • 14
  • 26

2 Answers2

2

I found a workaround if anybody is still looking for the answer:

componentDidMount() {
  this.mounted = true;

  Users.get().then(({ docs }) => {
    const users = docs.map(user => user.data());
      if(this.mounted) this.setState({ users });
  });
}

componentWillUnmount(){
  this.mounted = false;
}

this.mounted will be false when component is unmounted and setState will not work.

Muhammad Ovi
  • 1,053
  • 14
  • 26
  • This doesn't really abort the needless fetch or save network bandwith, it just suppresses the `React` warning about a memory leak – JayCodist Aug 09 '20 at 17:01
1

As Get is not a real-time method so there is no way to stop it on componentWillUnmont, it should not be getting called once your component is unmounted.

Jeff Adam
  • 103
  • 1
  • 11