Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Firestore `get` query on componentWillUnmount

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(){

}
like image 655
Muhammad Ovi Avatar asked Oct 16 '22 12:10

Muhammad Ovi


1 Answers

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.

like image 103
Muhammad Ovi Avatar answered Nov 01 '22 16:11

Muhammad Ovi