How to Implement Dynamic Menu (Drawer) items in React Native

Viewed 628

this is the scenario:

In Home Route, there is a dropdown which contains SubSystems and based on each subSystem menu items are different. So, when I change subSystem, Menu Items of drawer should update. I have implemented my drawer to get dynamic items like below code. But, the problem is that when then SubSystems are loaded I go to get the menu items after that I update the menuData state the whole component recompiles and it falls into a loop. How Can I Overcome This Problem ?

Home Route That I Select SubSystems from

Menu Items In Drawer that should update upon each subsystem

MY CODE StackNavigationManager.js

import {AuthContext} from './context';

const StackNavigationManager = () => {
const [menuData, setMenuData] = React.useState([]);

const authContext = React.useMemo(() => ({
validateMenuData: menuData => {
      setMenuData(menuData);
    },
  }));

const DrawerScreen = ({route, navigation}) => (
    <Drawer.Navigator
      drawerContent={props => <CustomDrawerContent {...props} />}>
      <Drawer.Screen
        name="HomeDrawer"
        component={Home} />
    </Drawer.Navigator>
  );

function CustomDrawerContent(props) {
    return (
      <SafeAreaView style={{flex: 1}}>
        <DrawerItemList {...props} />
        <FlatList
          data={menuData}
          keyExtractor={data => data.id.toString()}
          renderItem={({item}) => {
            return (
              <DrawerItem
                label={item.name}
                onPress={() => alert(item.id)}></DrawerItem>
            );
          }}
        />
      </SafeAreaView>
    );
  }

return (<AuthContext.Provider value={authContext}>
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName={initialRoute}>
          
          <Stack.Screen
            name="Home"
            component={DrawerScreen}
            options={{
              headerShown: false,
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>);

Context.js

import React from 'react';

export const AuthContext = React.createContext();

Home.js

import {AuthContext} from './context';

const home = ({navigation}) => {

const {validateMenuData} = React.useContext(AuthContext);

React.useEffect(() => {
   console.log('MOUNTED EFFECT');
   getSubSystems();

   return () => {
      isMounted = false;
      console.log('UNMOUNTED EFFECT');
    };
  }, []);

const getSubSystems = async () => {
    const subSystemModel = {
      isActive: true,
      isVisible: true,
    };
    fetchSubSystemData(
      subSystemModel,
      response => {
        if (response.list !== null) {
          let listData = [...response.list];
          
          fetchMenuAction(
            listData[0].id,
            response2 => {
              validateMenuData([...response2.list]);
            },
          );
        }
      },
      () => {},
    );
  };

0 Answers
Related