Kevvv
Kevvv

Reputation: 4023

Memory leak problem using withNavigationFocus in React Native

I have a listener set up using withNavigationFocus so that every time the user arrives on a screen or leaves the screen, a certain event gets triggered. But, I'm getting the following 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

const PleaseSignIn = props => {
    const {
        state: { authOpen },
        authModal
    } = useContext(Context)

    const focusListener = props.navigation.addListener('didFocus', () => {
        retrieveToken()     
    })

    const retrieveToken = async () => {
        try {
            const token = await AsyncStorage.getItem(LOGIN_TOKEN)
            if(!token) {
                authModal()
            }
        } catch (err) {
            throw new Error(err)
        }
    }

    if(!authOpen) {
        return (
            <View style={styles.container}> 
                <Auth navigation={props.navigation} />
                <Signup navigation={props.navigation}  />
                <Signin navigation={props.navigation} />
            </View>
        )
    }
    return props.children
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
})

export default withNavigationFocus(PleaseSignIn)

Upvotes: 0

Views: 669

Answers (1)

Oleg Levin
Oleg Levin

Reputation: 3621

After setting up an event listener, we must also stop listening to the event when the screen is unmounted. You have functional component and can subscribe and unsubscribe by using hook. Something like this:

 useEffect(() => {
 const focusListener = 
 props.navigation.addListener('didFocus', async() => {
      await retrieveToken();     
      });

   // returned function will be called on component 
    //unmount 
   return () => {
    focusListener.remove();
   }
   }, []);

Upvotes: 3

Related Questions