Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

479
Visualizações
How to remove listener in another screen - React Native

I want to alert a user before leaving a screen (NewNews.js). It works fine, but I do not want it to be called when he click the save button (PreviewSave.js). Remove listeners are no longer maintained.

After pressing save button the customAlert is triggered. I would like to remove the listener in save function (PreviewSave.js) but it is not working.

NewNews.js

let exitListener;

useEffect(() => {
    exitListener = navigation.addListener('beforeRemove', e => {
        e.preventDefault();
        customAlert(                 // <- alerting user and waiting for his response
            string.exit,
            string.exitMore,

            () => {
                navigation.dispatch(e.data.action);
            },
            () => {
                console.log('Cancel Pressed');
            },
            string.understand,
        );

    return () => exitListener()
    },[]);

const renderScene = (...) => {
    ...
    return (
        <PreviewSave ...
            navigation={navigation}
            listener={exitListener}.        // here I try to pass the listener
        />
    );
}

return (
    ...
    <TavView ...
        renderScene={renderScene} ... />
);

PreviewSave.js

...
const save = async () => {
    // listener()
    // listener.remove();
    listener;                              // none of these work

    if (route?.item) {
        navigation.goBack();
        navigation.navigate(string.articles, {
            screen: string.article
        });
    } else {
        navigation.goBack();
    }
};

return (
    ...
    <TouchableOpacity onPress={() => save()}>
         <Text>{string.save}</Text>
    </TouchableOpacity>

);

dependencies

    "react": "^17.0.2",
    "react-native": "^0.67.4",
    "@react-navigation/bottom-tabs": "^6.0.9",
    "@react-navigation/drawer": "^6.1.8",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/stack": "^6.0.11"
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Actually, your variable is going to be reset on the next render batch, and the function to remove the listener will be lost. To retain the function on consequent renders, you need to use useRef

let exitListener = useRef();

useEffect(() => {
    exitListener.current = navigation.addListener('beforeRemove', e => {
        e.preventDefault();
        customAlert(                 // <- alerting user and waiting for his response
            string.exit,
            string.exitMore,

            () => {
                navigation.dispatch(e.data.action);
            },
            () => {
                console.log('Cancel Pressed');
            },
            string.understand,
        );

    return exitListener;
    // return () => exitListener()
    });

And then pass it.

const renderScene = (...) => {
    ...
    return (
        <PreviewSave ...
            navigation={navigation}
            listener={exitListener.current}
        />
    );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda