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

Maintain a list of words in Java 8

0  Asked on August 30, 2020 by sansel

         

C# Entity Framework: Update Only First Batch Records and Stop

2  Asked on August 29, 2020 by artportraitdesign1

       

Split a string based on a delimiter but shift across 1

3  Asked on August 28, 2020 by adam-sewell

     

Using xattr to display macOS file comments

1  Asked on August 26, 2020 by philip-kearns

     

Not able to delete n

3  Asked on August 26, 2020 by user13645394

       

enable_if compilation question void = nullptr

2  Asked on August 25, 2020 by notaorb

 

R Comparing Two Data Frames without using Merge

1  Asked on August 19, 2020 by randomthinker

   

How Can I create Blue View in SwiftUI?

1  Asked on August 19, 2020 by davis-zhang

   

Ask a Question

Get help from others!

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