Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
how to prevent stacking function callbacks while exiting a screen react/react-native

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can try this:

useEffect(()=>{
  navigation.addListener('beforeRemove', () => {
    console.log('check this', selectedProducts);
    if (!selectedProducts) {
      return;
    }
    dispatch(addToCartMultipleQty(selectedProducts));
  });  
  return () => {
    navigation.removeListener('beforeRemove');
  }
}, [selectedProducts])
about 4 years ago · Juan Pablo Isaza Denunciar

0

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]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda