Home > Enterprise >  I got undefined, When used Context Hooks to pass values to my components
I got undefined, When used Context Hooks to pass values to my components

Time:11-18

I'm working on a React Native app that will use expo and context hooks to pass value between components. The problem is that when I introduce MapView in the context and use the value inside my map component, unfortunately, I am getting undefined is not an object(evaluating "usePlaceContext.userLocation"). I try to use it inside the map.jsx is working. I do not know what I am doing wrong there. Can someone help and explain the problem? Thanks.

placeContext.jsx:

import { createContext, useContext, useState, useEffect } from "react";
import axios from "axios";
import MapView, { Marker } from "react-native-maps";
import * as Location from "expo-location";

const PlaceContext = createContext();

export const ContextProvider = ({ children }) => {
  const [places, setPlaces] = useState([]);
  const [filterPlaces, setFilterPlaces] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [locality, setLocality] = useState({
    latitude: 37.78825,
    longitude: 11.50078,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  });

  useEffect(() => {
    axios
      .post(
        "https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
      )
      .then((response) => setPlaces(response.data))
      .catch((error) => setIsError(error))
      .finally(() => setIsLoading(true));
  }, []);

  const userLocation = async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") {
      setErrorMsg("Permission denied");
    }
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
    });
    setLocality({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    });

    console.log(
      `my location:${(location.coords.latitude, location.coords.longitude)}`
    );
  };

  return (
    <PlaceContext.Provider
      value={{
        places,
        isLoading,
        isError,
        setSearchValue,
        searchValue,
        locality,
        userLocation,
      }}
    >
      {children}
    </PlaceContext.Provider>
  );
};

export const usePlaceContext = () => useContext(PlaceContext);

HomeScreen.jsx:

import {
  StyleSheet,
  ImageBackground,
  SafeAreaView,
  View,
  Text,
} from "react-native";
import { StatusBar } from "expo-status-bar";
import Search from "../../components/search/Search";
import AppLogo from "../../components/appLogo/AppLogo";
import PlayGrounds from "../../components/places/PlayGrounds";
import backgroundImage from "../../../assets/images/imageBG.jpeg";
import { ContextProvider } from "../../context/placeContext";
import { colors } from "../../../assets/theme/theme";

const HomeScreen = () => {
  return (
    <ImageBackground source={backgroundImage} style={styles.container}>
      <ContextProvider>
        <PlayGrounds
          ListHeaderComponent={() => (
            <SafeAreaView style={styles.frame}>
              <AppLogo />
              <Search />
              <View style={styles.locationContainer}>
                <Text style={styles.myLocation}>I here</Text>
              </View>
            </SafeAreaView>
          )}
        />
        <StatusBar style="default" />
      </ContextProvider>
    </ImageBackground>
  );
};

export default HomeScreen;

Map.jsx:

import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  TextInput,
  Dimensions,
  SafeAreaView,
} from "react-native";
import { colors } from "../../../assets/theme/theme";
import MapView, { Marker } from "react-native-maps";
import { usePlaceContext } from "../../context/placeContext";
import { MaterialIcons } from "@expo/vector-icons";
import SafeViewAndroid from "../../components/androidSafeAreaView/AndroidSafeAreaView";

const MapScreen = () => {
  const [searchText, setSearchText] = useState("");
  const { userLocation, locality } = usePlaceContext();

  useEffect(() => {
    userLocation();
  }, []);

  return (
    <SafeAreaView style={SafeViewAndroid.AndroidSafeArea}>
      <SafeAreaView style={styles.mapContainer}>
        <View style={styles.topItems}>
          <MaterialIcons
            style={styles.icon}
            name="my-location"
            size={20}
            color="black"
            onPress={userLocation}
          />
          <TextInput
            style={styles.input}
            onChangeText={(value) => setSearchText(value)}
            value={searchText}
            placeholder="Search a playground here..."
            placeholderTextColor={`${colors.gray}`}
          />
        </View>
        <SafeAreaView style={styles.container}>
          <MapView style={styles.map} region={locality}>
            <Marker coordinate={locality} title="Marker" />
          </MapView>
        </SafeAreaView>
      </SafeAreaView>
    </SafeAreaView>
  );
};

export default MapScreen;

error app

CodePudding user response:

Check Map.jsx not is a child a of Homescreen.jsx which has access to ConfigProvider.

  • Related