TransWikia.com

Get values from useEffect hook and display in React's functional components

Stack Overflow Asked by scriobh on January 5, 2022

I’m a newbie to React. Trying to get location coordinates in a page and want to display the latitude and longitude but not sure how to get the value from getCurrentPostion function which is being called in useEffect hook here. Could anyone please help?

Here’s a gist of my code.

const getCurrentPosition = async () => {
  const {
    coords: { latitude, longitude },
  } = await Geolocation.getCurrentPosition();
  return { latitude, longitude };
};

const TestComponent = () => {
  useEffect(() => {
    getCurrentPosition().then((res) => console.log('res', res));
  });
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates ( Yet to be displayed ) </div>
      </IonContent>
    </IonPage>
  );
};

2 Answers

const TestComponent = () => {
 const [coordinates, setCoordinates] = 
useState({latitude:"", longitude:""});
const getCurrentPosition = async () => {
  const {
    coords: { latitude, longitude },
  } = await Geolocation.getCurrentPosition();
  setCoordinates({latitude, longitude})
};
  useEffect(() => {
    getCurrentPosition();
  });
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates {coordinates.latitude}</div>
      </IonContent>
    </IonPage>
  );
};

Answered by Martin Červenka on January 5, 2022

Those values should live on the state somewhere. So for example:

const TestComponent = () => {
  const [coord, setCoords] = useState(null);
  useEffect(() => {
    getCurrentPosition().then((res) => {
      setCoords(res);
    }
  });
  // Now you have access too coords here
  if (!coords) return <div>Loading..<div> // handle waiting for the request
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates { coords.latitude } { coords.longitude } </div>
      </IonContent>
    </IonPage>
  );
};

Answered by BravoZulu on January 5, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP