Skip to content

Commit 5d571f8

Browse files
committed
Add the react unmount
1 parent 4c40623 commit 5d571f8

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

src/components/cart/cart-item.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useEffect, useState } from 'react';
1+
import React, { useEffect, useState, useRef } from 'react';
22
import {isEmpty} from "lodash";
33
import Image from '../image';
44
import { deleteCartItem, updateCart } from '../../utils/cart';
@@ -14,6 +14,29 @@ const CartItem = ( {
1414
const [removingProduct, setRemovingProduct] = useState( false );
1515
const productImg = item?.data?.images?.[0] ?? '';
1616

17+
/**
18+
* isMounted is used so that we can set it's value to false
19+
* when the component is unmounted.
20+
* This is done so that setState ( e.g setRemovingProduct ) in asynchronous calls
21+
* such as axios.post, do not get executed when component leaves the DOM
22+
* due to product/item deletion.
23+
* If we do not do this as unsubscription, we will get
24+
* "React memory leak warning- Can't perform a React state update on an unmounted component"
25+
*
26+
* @see https://dev.to/jexperton/how-to-fix-the-react-memory-leak-warning-d4i
27+
* @type {React.MutableRefObject<boolean>}
28+
*/
29+
const isMounted = useRef( false );
30+
31+
useEffect( () => {
32+
isMounted.current = true
33+
34+
// When component is unmounted, set isMounted.current to false.
35+
return () => {
36+
isMounted.current = false
37+
}
38+
}, [] )
39+
1740
/*
1841
* Handle remove product click.
1942
*
@@ -25,9 +48,12 @@ const CartItem = ( {
2548
const handleRemoveProductClick = ( event, cartKey ) => {
2649
event.stopPropagation();
2750

28-
if ( !updatingProduct ) {
29-
deleteCartItem( cartKey, setCart, setRemovingProduct );
51+
// If the component is unmounted, or still previous item update request is in process, then return.
52+
if ( !isMounted || updatingProduct ) {
53+
return;
3054
}
55+
56+
deleteCartItem( cartKey, setCart, setRemovingProduct );
3157
};
3258

3359
/*

0 commit comments

Comments
 (0)