0

I am stuck on some Basic problem and don't know what should I look for... I have tried to work with Props but I failed.

I have two Files.

First File Map.js


export default function Map() {
  return (
    <View style={styles.container}>
      <MapView style={styles.map}  
      initialRegion={{
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    }}
  />
    </View>
  );
}

Second File CurrentPossition.js

export default function CurrentPossition() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [copiedText] = useState('')

  useEffect(() => {
    (async () => {
      if (Platform.OS === 'android' && !Constants.isDevice) {
        setErrorMsg(
          'Oops, this will not work on Snack in an Android emulator. Try it on your device!'
        );
        return;
      }
      let { status } = await Location.requestPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);

    })();
  }, []);

    let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location.coords.latitude);
  }

I would like to pass the Value from the CurrentPossition.js Variable let text in to the latitude:parameter of <MapView /> component of the Map.js File.

 <MapView style={styles.map}  
      initialRegion={{
      latitude: {text},
      }}
  />

How can I do this?


2nd Try

My Map.JS looks now like this, but I don't become the right coordinates. When I log the Value of text - I just become Waiting... that's the string from const [text, setText] = React.useState("Waiting...");


export const MyContext = React.createContext();

export default function Map() {
  const [text, setText] = React.useState("Waiting...");
  console.log(text);
  return (
    <MyContext.Provider value={{ text, setText }}>

      <View style={styles.container}>
        <MapView
          style={styles.map}
          initialRegion={{
            latitude: text,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
        />
      </View>

  </MyContext.Provider>
  ); 
}```
2
  • are you using a state managment such as Redux ? Commented Mar 11, 2021 at 15:57
  • MapView is not a child component of CurrentPossition. So you can't just pass it's local state to MapView directly. Either store a global state (redux/flux), or use localStorage, or useContext to pass this value. Post the entire code where you are using these components. And then I can suggest which of these options would be better. Commented Mar 11, 2021 at 16:01

1 Answer 1

1

Add context in a common parent of both components and access it in the child components:

  • Create the context and export it so that the child components can import it when needed

    export const MyContext = React.createContext();
     // Create state in the parent component
     const [text, setText] = React.useState("Waiting...");
    
  • Wrap the children in this provider

    <MyContext.Provider value={{ text, setText }}>
     // children
    </MyContext.Provider>;
    
  • in Map.js

    export default function Map() {
    return (
      <MyContext.Consumer>
        {({ text }) => (
          <View style={styles.container}>
            <MapView
              style={styles.map}
              initialRegion={{
                latitude: text,
                longitude: -122.4324,
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421,
              }}
            />
          </View>
        )}
      </MyContext.Consumer>
    );
    

    }

  • in CurrentPossition.js

    import {MyContext} from "./somewhere"
    export default function CurrentPossition() {
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [copiedText] = useState('')
    const {setText} = React.useContext(MyContext)
    
    useEffect(() => {
      (async () => {
        if (Platform.OS === 'android' && !Constants.isDevice) {
          setErrorMsg(
            'Oops, this will not work on Snack in an Android emulator. Try it on your device!'
          );
          return;
        }
        let { status } = await Location.requestPermissionsAsync();
        if (status !== 'granted') {
          setErrorMsg('Permission to access location was denied');
          return;
        }
    
        let location = await Location.getCurrentPositionAsync({});
        setLocation(location);
    
      })();
    }, []);
    
    if (errorMsg) {
      setText(errorMsg);
    } else if (location) {
      setText(JSON.stringify(location.coords.latitude))
    }
    
Sign up to request clarification or add additional context in comments.

6 Comments

THX for the fast answer!!! My 2nd Try I become now "Waiting..." when I console.log text in Map.js.
So is this what you expected or should it have been updated at that point?
I expected the value of let text = JSON.stringify(location.coords.latitude);
Cadn you check whether the setText is reached and executed? Because if it fires, the text should be updated.
When I try to Log setText, I become [Function bound dispatchAction]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.