Home > Blockchain >  how to prevent stacking function callbacks while exiting a screen react/react-native
how to prevent stacking function callbacks while exiting a screen react/react-native

Time:07-12

I have a local state selectedProducts holding a number representing the number of products the client has selected, while exiting the screen I want to update the number in redux so it can be viewed in the cart on a different screen.

but every time my local selectedProducts updates it stacks another function call on beforeRemove event

I know this is a noob problem but I've spent hours trying to find a solution to this problem and advice would be very helpful :)

    useEffect(()=>{
     navigation.addListener('beforeRemove', () => {
     console.log('check this', selectedProducts);
     if (!selectedProducts) {
      return;
     }
     dispatch(addToCartMultipleQty(selectedProducts));
     });
    },[selectedProducts])

selectedProducts is a number state whose initial value is null and on a button click event its value is either incremented or decremented by 1, if its previous value is null then its value is set to 1

Note: I just want to update selectedProducts state's latest value only once in redux when the screen is about to be exited/unmonted

CodePudding user response:

You can try this:

useEffect(()=>{
  navigation.addListener('beforeRemove', () => {
    console.log('check this', selectedProducts);
    if (!selectedProducts) {
      return;
    }
    dispatch(addToCartMultipleQty(selectedProducts));
  });  
  return () => {
    navigation.removeListener('beforeRemove');
  }
}, [selectedProducts])

CodePudding user response:

Add that in return at the end of useEffect it will work as componentWillUnmount in functional component

useEffect(() => {
    return () => {
        // Anything in here is fired on component unmount.
    }
}, [])

Edit: In Your case

  useEffect(() => {
    console.log('check this', selectedProducts);
    if (!selectedProducts) {
      return;
    }
    return () => {
      // Anything in here is fired on component unmount.
      if (selectedProducts) {
        dispatch(addToCartMultipleQty(selectedProducts));
      }
    };
  }, [selectedProducts]);
  • Related