0

so.. i tried some similar answer here but non of theme work, and need to listen to live update from firestore db and i have to work with class component

always get this 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.

my code:

class Exchange extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      exchangePrice: 0,
      newExchangePrice: "",
    };
    this.updateExchangePrice = this.updateExchangePrice.bind(this);
  }

  updateExchangePrice() {
    const docRef = doc(db, "exchange", "exchange");
    if (
      this.state.newExchangePrice !== "" &&
      this.state.newExchangePrice !== 0
    ) {
      updateDoc(docRef, {
        exchange_price: Number(this.state.newExchangePrice),
      });
      this.setState({ newExchangePrice: "" });
    }
  }
  componentDidMount() {
    const exchanges = collection(db, "exchange");
    onSnapshot(exchanges, (x) => {
      x.docs.forEach((doc) => {
        if (doc.data().exchange_price !== this.state.exchangePrice) {
          this.setState({ exchangePrice: doc.data().exchange_price });
        }
      });
    });

  }

ripouu
  • 93
  • 8
  • 1
    The error which you are getting suggests that you should do a clean-up as soon as the component is un-mounted from the DOM tree. You can use ComponentWillUnmount() life-cycle method and do the necessary un-subscriptions there. You may have a look at the [React official doc](https://reactjs.org/docs/react-component.html#componentwillunmount) to explore more on the method. Also, you may have a look at the [Stackoverflow case](https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component). – Mousumi Roy Mar 21 '22 at 09:04

1 Answers1

0

Memory leaks is an issue when implementing React code, when using side-effects. Explore more on this from here. Some side-effects require clean-up. And that clean-up can be done by the use of ComponentWillUnmount() life-cycle method in a class based component in React. Using the ComponentWillUnmount() method, you can do the necessary un-subscriptions there that you previously implemented.

You may have a look at the React official doc to explore more on the method.

Also, you may have a look at the Stackoverflow case.

Mousumi Roy
  • 609
  • 1
  • 6