-3

I'm creating an application using React Native CLI and RealmDB to persist the data locally. On the product list screen the useEffect function returns the 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 a useEffect cleanup function.

Code:

  const [didMount, setDidMount] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    setDidMount(true);

    async function loadProducts() {
      const realm = await getRealm();

      try {
        if (!didMount) return;
        const data: Product[] = realm
          .objects('Product')
          .sorted('id', true) as any;

        setProducts(data);
      } catch (err) {
        console.error(err);
      }
    }

    loadProducts();

    return function cleanup() {
      setDidMount(false);
    };
  }, []);

1 Answers1

1

From this post.

You can't set states in the cleanup functions, but instead should ensure no further state updates are caused.

const [products, setProducts] = useState<Product[]>([]);

useEffect(() => {
  let updateProducts = true;

  getRealm().then((realm) => {
    try {
      const data = realm
          .objects('Product')
          .sorted('id', true) as Product[];

      if (updateProducts) setProducts(data);
    } catch (err) {
      console.error(err);
    }
  });

  return () => {
    updateProducts = false;
  };
}, []);
MrCodingB
  • 2,284
  • 1
  • 9
  • 22