AnswerBun.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!

Related Questions

RGB to hex and hex to RGB

51  Asked on January 3, 2022 by sindar

       

Setup dictionary lazily

8  Asked on January 3, 2022

     

Iterating over directories with Gulp?

5  Asked on January 3, 2022 by nathan-rutman

   

converting a csv file to json + python with specific json format

4  Asked on January 3, 2022 by hattricknz

     

How do you create a gRPC client in .NET Framework?

2  Asked on January 3, 2022 by rich-shipley

     

How do I switch from a merged branch to an new branch?

2  Asked on January 3, 2022 by mohammad-23

   

How can i edit an array in a JSON file from node?

1  Asked on January 3, 2022 by thomas-bouasli

       

Ask a Question

Get help from others!

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