Home > Software engineering >  Getting "Invalid Hook Call" Error when trying to us Logout Button in Drawer.Navigator with
Getting "Invalid Hook Call" Error when trying to us Logout Button in Drawer.Navigator with

Time:01-16

Im trying to implement a Logout button in the DrawerNavigator, which should logout via a function in my context and should then change the navigation with the useNavigation hook. However when it loads the component, I get the following error: enter image description here enter image description here enter image description here

Here is my Code which im trying to execute:

import React, { useContext } from "react";
import { View, Text, Alert, StyleSheet, TouchableOpacity } from "react-native";
import {
  DrawerContentScrollView,
  DrawerItemList,
  DrawerItem,
} from "@react-navigation/drawer";
import { useNavigation } from "@react-navigation/native";
import AuthContext from "../store/auth-context";

const CustomSidebarMenu = (props) => {
  const navigation = useNavigation();
  const authCtx = useContext(AuthContext);
  return (
    <View style={stylesSidebar.sideMenuContainer}>
      <DrawerContentScrollView {...props}>
        <DrawerItemList {...props} />
        <TouchableOpacity
          style={stylesSidebar.buttonStyle}
          onPress={() => {
            authCtx.logout();
            navigation.replace("Login");
          }}
          activeOpacity={0.5}
        >
          <Text style={stylesSidebar.buttonTextStyle}>Logout</Text>
        </TouchableOpacity>
      </DrawerContentScrollView>
    </View>
  );
};

export default CustomSidebarMenu;

useCallback code:

 const logoutHandler = useCallback(async () => {
    setToken(null);
    await AsyncStorage.removeItem('token');
    await AsyncStorage.removeItem('expirationTime');

    if (logoutTimer) {
      clearTimeout(logoutTimer);
    }
  }, []);

CodePudding user response:

From apollo docs: Note that you cannot use the useNavigation hook inside the drawerContent since useNavigation is only available inside screens. You get a navigation prop for your drawerContent which you can use instead

Try props.navigation.replace("Login"); instead

Same issue you are facing on Github here as well: https://github.com/react-navigation/react-navigation/issues/7725

  •  Tags:  
  • Related