React native side drawer not closing

拟墨画扇 提交于 2021-01-07 06:34:19

问题


I have a react native side drawer which is not responding at all, also when am consoling the state it is not coming. and initially the drawer is open and not closing or responding upon initial render:

My exact code is written below:

import React, { useEffect, useState } from "react";
import {
  View,
  ScrollView,
  ActivityIndicator,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
} from "react-native";
import AsyncStorage from "@react-native-community/async-storage";
import MenuDrawer from "react-native-side-drawer";
import {
  getUserObject,
  getSelectedChildId,
  clearData,
  setSelectedChildId,
} from "../../commons/StorageHelper";
import DropDownPicker from "react-native-dropdown-picker";
import Icon from "react-native-vector-icons/FontAwesome";
import HomeTabAssessmentCardComponent from "./components/HomeTabAssessmentCardComponent";
import { API } from "../../api";
import HomeTabOverAllDevelopmentCardComponent from "./components/HomeTabOverAllDevelopmentCardComponent";
import HomeTabPhysicalGrowthCardComponent from "./components/HomeTabPhysicalGrowthCardComponent";
import HomeTabPersonalCoachCardComponent from "./components/HomeTabPersonalCoachCardComponent";
import HomeTabPremiumCardComponent from "./components/HomeTabPremiumCardComponent";
import HomeTabPrimeCardComponent from "./components/HomeTabPrimeCardComponent";
import HomeTabWeekWiseImagesCardComponent from "./components/HomeTabWeekWiseImagesCardComponent";
import { Spacer } from "../../components/spacer";
import HomeTabVaccinationCardComponent from "./components/HomeTabVaccinationCardComponent";
import { SafeAreaView } from "react-native-safe-area-context";
import HomeTabDailyReadsCardComponent from "./components/HomeTabDailyReadsCardComponent";
import { isValidObject } from "../../utils/baseUtils";

export default function HomeTabScreen(props) {
  const { navigation } = props;
  const [loading, setLoading] = useState(false);

  //child related
  const [User, setUser] = useState(null);
  const [mSChildId, setSChildId] = useState(null);
  const [loadApi, setLoadApi] = useState(true);
  const [mChild, setSelectedChild] = useState(null);
  // Assessment card
  const [mAssessmentList, setAssessmentList] = useState([]);
  const [title, setTitle] = useState("");
  const [text, setText] = useState("");
  const [userObject, setUserObject] = useState(null);
  const [gcPhysicalGrowth, setGCPhysicalGrowth] = useState();
  const [childId, setChild] = useState(null);
  const [selectedChildObj, setSelectedChildObj] = useState(null);
  // Vaccination card
  const [mVaccinationList, setVaccinationList] = useState([]);
  const [vaccineTitle, setVaccineTitle] = useState("");
  const [vaccineText, setVaccineText] = useState("");
  // Week wise Images card
  const [mWeekWiseMediaList, setWeekWiseMedialist] = useState([]);
  // Personal coach card
  const [mPersonalCoach, setPersonalCoach] = useState([]);
  // Daily Reads card
  const [mDailyReadsList, setDailyReadsList] = useState([]);
  // Prime Card
  const [mPrimeCard, setPrimeCard] = useState(null);
  // side drawer
  const [open, setOpen] = useState(false);
  useEffect(() => {
    // console.log('useEffect - user', User);
    // console.log('useEffect - mSChildId', mSChildId);

    if (isValidObject(User) && isValidObject(mSChildId)) {
      console.log("useEffect true");
      console.log("useEffect true - user", User);
      if (loadApi == true) {
        getHomeTabMainAPI();
        setLoadApi(false);
        setSelectedChild(getChildFromUserChildrenList());
      }
    } else {
      console.log("useEffect false");
      if (!isValidObject(User) || !isValidObject(mSChildId)) {
        console.log(
          "!!!!!! Calling get user data !!!! Child Id  ",
          mSChildId,
          " User Valid ",
          isValidObject(User)
        );
        getUserData();
      }
    }
  }, [User, mSChildId, loadApi]);

  const getChildFromUserChildrenList = () => {
    if (User.children.length > 0) {
      for (let i = 0; i < User.children.length; i++) {
        if (User.children[i].id === mSChildId) {
          return User.children[i];
        }
      }
    }
  };

  const getHomeTabMainAPI = async () => {
    try {
      console.log(" mSChildId ", mSChildId);
      const response = await API.get(`some url`);
      console.log(
        "🚀 ~ file: HomeTabScreen.js ~ line 94 ~ getHomeTabMainAPI ~ response",
        response
      );
      //console.log('getHomeTabMainAPI - response', response);
      setGCPhysicalGrowth(response.data.content.gc_physical_growth);
      setAssessmentList(response.data.content.assessments.data);
      setTitle(response.data.content.assessments.title);
      setText(response.data.content.assessments.text);
      if (response.data.content.media_cards != undefined) {
        setWeekWiseMedialist(response.data.content.media_cards.data);
      } else {
        setWeekWiseMedialist(null);
      }
      if (
        response.data.content != null &&
        response.data.content.expert != undefined &&
        response.data.content.expert != null &&
        response.data.content.expert.data != null
      ) {
        var expertArray = [response.data.content.expert.data];
        console.log("getHomeTabMainAPI showing expert data ");
        setPersonalCoach(expertArray);
      }
      if (
        response.data.content != null &&
        response.data.content.prime_card != undefined &&
        response.data.content.prime_card != null
      ) {
        var primeArray = [response.data.content.prime_card];
        console.log("getHomeTabMainAPI showing prime card data ");
        setPrimeCard(response.data.content.prime_card);
      } else {
        setPrimeCard(null);
      }

      // vaccination Api call
      getHomeTabVaccinationAPI();
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  const getHomeTabVaccinationAPI = async () => {
    try {
      const vaccineResponse = await API.get(`some url`);
      console.log("getHomeTabVaccinationAPI -> response ", vaccineResponse);
      if (
        vaccineResponse.data.content.data.vaccination_list != null &&
        vaccineResponse.data.content.data.vaccination_list.length > 0 &&
        vaccineResponse.data.content.data.vaccination_list[0].vaccine_list !=
          null &&
        vaccineResponse.data.content.data.vaccination_list[0].vaccine_list
          .length > 0
      ) {
        setVaccinationList(
          vaccineResponse.data.content.data.vaccination_list[0].vaccine_list
        );
        setVaccineTitle(vaccineResponse.data.content.title);
        setVaccineText(vaccineResponse.data.content.text);
        getHomeTabDailyReadsApi();
      }
    } catch (e) {
      console.log("getHomeTabVaccinationAPI -> error ", e);
    }
  };

  const getHomeTabDailyReadsApi = async () => {
    try {
      const dailyReadsResponse = await API.get(`some url`);
      console.log("getHomeTabDailyReadsApi -> got response ");
      if (
        dailyReadsResponse.data != null &&
        dailyReadsResponse.data.content != null &&
        dailyReadsResponse.data.content.length > 0 != null
      ) {
        setDailyReadsList(dailyReadsResponse.data.content);
      }
    } catch (e) {
      console.log("getHomeTabDailyReadsApi -> error ", e);
    }
  };

  const logoutHandler = async () => {
    await clearData();
    navigation.navigate("login");
  };

  const toggleOpen = () => {
    console.log("drawer open/close", open);
    setOpen(!open);
    console.log(" after drawer open/close", open);
  };
  const drawerContent = () => {
    return (
      <View>
        <TouchableOpacity
          style={{
            marginLeft: "80%",
          }}
          onPress={() => logoutHandler()}
        >
          <Text style={{ fontSize: 15, fontWeight: "bold", color: "#000" }}>
            Log out
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => toggleOpen()}>
          <Text>close</Text>
        </TouchableOpacity>
      </View>
    );
  };

  const getUserData = async () => {
    console.log("getUserData start");
    if (!isValidObject(User)) {
      const user = await getUserObject();
      setUser(user);
    }
    const cid = await getSelectedChildId();
    if (isValidObject(cid)) {
      setSChildId(cid);
    } else {
      // We need to set it from user object
      if (isValidObject(User)) {
        const cid = User.children ? User.children[0].id : null;
        setSChildId(cid);
      }
    }
  };

  const handleChangeChild = (id) => {
    setSChildId(id);
    setSelectedChildId(id);
    setLoadApi(true);
  };

  const clearChildData = () => {
    // setLoading(true);
    // setWeekWiseMedialist(null);
    // setPrimeCard(null);
  };

  const getSelectedChildId = () => {
    try {
      AsyncStorage.getItem("selected_child_id").then((result) => {
        console.log("getSelectedChildId - result", result);

        setSChildId(JSON.parse(result));
        // return JSON.parse(result);
      });
    } catch (e) {}
  };

  const getSelectedChild = () => {
    var selectedCh = null;
    try {
      User.children.map((item, index) => {
        if (item.id == mSChildId) {
          selectedCh = item;
          return selectedCh;
        }
      });
    } catch (e) {}
  };

  return (
    <SafeAreaView
      style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
    >
      {loading ? (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <ActivityIndicator size="large" color="#FE017E" />
        </View>
      ) : (
        <View
          style={{
            flex: 1,
            backgroundColor: "#fff",
            flex: 1,
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <MenuDrawer
            open={open}
            drawerContent={drawerContent()}
            drawerPercentage={45}
            animationTime={250}
            overlay={true}
            opacity={0.4}
          >
            <ScrollView>
              <View
                style={{
                  backgroundColor: "#fff",
                  padding: 10,
                  justifyContent: "space-between",
                  flexDirection: "row",
                }}
              >
                <TouchableOpacity onPress={() => toggleOpen()}>
                  <Icon size={15} name="bars" />
                </TouchableOpacity>

                <TouchableOpacity
                  style={{
                    marginLeft: "80%",
                  }}
                  onPress={() => logoutHandler()}
                >
                  <Text
                    style={{ fontSize: 15, fontWeight: "bold", color: "#000" }}
                  >
                    Log out
                  </Text>
                </TouchableOpacity>
              </View>
              {console.log("view user - ", isValidObject(User))}
              {User != null &&
                User.children != undefined &&
                User.children != null &&
                User.children.length > 0 && (
                  <DropDownPicker
                    items={User.children.map((item) => {
                      return {
                        label: item.name,
                        value: item,
                        icon: () =>
                          item.gender === "male" ? (
                            <Image
                              source={{
                                uri:
                                  "https://cdn3.iconfinder.com/data/icons/materia-human/24/013_042_newborn_infant_child_baby-512.png",
                              }}
                              style={{ height: 20, width: 20 }}
                            />
                          ) : (
                            <Image
                              source={{
                                uri:
                                  "https://cdn3.iconfinder.com/data/icons/materia-human/24/013_042_newborn_infant_child_baby-512.png",
                              }}
                              style={{ height: 20, width: 20 }}
                            />
                          ),
                      };
                    })}
                    onChangeItem={(item) => {
                      console.log("onChangeItem item", item.value.id);
                      if (item.value.id != mSChildId) {
                        handleChangeChild(item.value.id);
                      }
                    }}
                    containerStyle={{ height: 40 }}
                    defaultValue={User.children[0]}
                    itemStyle={{
                      justifyContent: "flex-start",
                      fontWeight: "bold",
                      fontSize: 20,
                    }}
                    style={{
                      borderTopColor: "#fff",
                    }}
                    labelStyle={{
                      marginLeft: "15%",
                      fontWeight: "bold",
                      fontSize: 15,
                      color: "#000",
                    }}
                  />
                )}
              {/* // </View> */}
              <View style={{ paddingBottom: 58 }}>
                {mWeekWiseMediaList !== null &&
                  mWeekWiseMediaList.length > 0 && (
                    <HomeTabWeekWiseImagesCardComponent
                      data={mWeekWiseMediaList}
                    />
                  )}
                {
                  console.log("view mAssessmentList - " + mAssessmentList)
                  // CHECK BELOW childrenObject....You may need just 1 object instead of MAP array...
                  // Might want to use find() instead of map
                }
                {isValidObject(mAssessmentList) && isValidObject(mChild) && (
                  <HomeTabAssessmentCardComponent
                    data={mAssessmentList}
                    title={title}
                    text={text}
                    navigation={props}
                    childId={mSChildId}
                    selectedChild={mChild}
                  />
                )}
                {console.log("view primeCard", mPrimeCard)}
                {mPrimeCard != undefined && mPrimeCard != null && (
                  <HomeTabPrimeCardComponent
                    data={mPrimeCard}
                    navigation={props}
                  />
                )}
                {gcPhysicalGrowth &&
                  gcPhysicalGrowth !== null &&
                  gcPhysicalGrowth !== undefined && (
                    <HomeTabPhysicalGrowthCardComponent
                      data={gcPhysicalGrowth}
                      navigation={navigation}
                    />
                  )}

                {console.log("view mVaccinationList - " + mVaccinationList)}
                {mVaccinationList &&
                  mVaccinationList != "" &&
                  mVaccinationList != null &&
                  mVaccinationList.length > 1 &&
                  mSChildId != null &&
                  User != null &&
                  User.children != null &&
                  User.children.length > 0 && (
                    <HomeTabVaccinationCardComponent
                      data={mVaccinationList}
                      title={vaccineTitle}
                      text={vaccineText}
                      navigation={props}
                      childId={mSChildId}
                      selectedChild={mChild}
                    />
                  )}
                {console.log("view mDailyReadsList - " + mDailyReadsList)}
                {mDailyReadsList &&
                  mDailyReadsList != "" &&
                  mDailyReadsList != null &&
                  mDailyReadsList.length > 1 &&
                  mSChildId != null &&
                  User != null &&
                  User.children != null &&
                  User.children.length > 0 && (
                    <HomeTabDailyReadsCardComponent
                      data={mDailyReadsList}
                      navigation={props}
                      childId={mSChildId}
                      selectedChild={mChild}
                    />
                  )}
                {console.log("view  - mPersonalCoach" + mPersonalCoach)}
                {mPersonalCoach != null && mPersonalCoach.length > 0 && (
                  <HomeTabPersonalCoachCardComponent
                    data={mPersonalCoach}
                    navigation={props}
                  />
                )}
              </View>
            </ScrollView>
          </MenuDrawer>
        </View>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 30,
    zIndex: 0,
  },
  animatedBox: {
    flex: 1,
    backgroundColor: "#38C8EC",
    padding: 10,
  },
  body: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#F04812",
  },
});

I have been stuck with this since a long time now, any kind of lead would be appreciated, please let me know where I have gone wrong Thank you in advance

来源:https://stackoverflow.com/questions/65289751/react-native-side-drawer-not-closing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!