Alireza
Alireza

Reputation: 171

How can I use setState to save current location in react native?

I use this code to get current location from user, but now I have a notice when I use setState to save latitude and longitude to states.

ReferenceError: setState is not defined

 async componentDidMount(){
     const { status } = await Expo.Permissions.askAsync(Expo.Permissions.LOCATION);
       if (status === 'granted') {
           const location = await Expo.Location.getCurrentPositionAsync({
             enableHighAccuracy: true,
           });
           setState({
             lat:JSON.stringify(location.coords.latitude),
             long:JSON.stringify(location.coords.longitude),
           });
       }
 }

How can I save location to states?

Upvotes: 0

Views: 299

Answers (1)

Jebin Benny
Jebin Benny

Reputation: 951

You can setState with this.

in your constructor add state variables,

constructor(props) {
        super(props);
        this.state = {
            ...
            lat: 0.000,
            long: 0.000,
            ...
        };
    }

Then add this to method.

async componentDidMount(){
     const { status } = await Expo.Permissions.askAsync(Expo.Permissions.LOCATION);
       if (status === 'granted') {
           const location = await Expo.Location.getCurrentPositionAsync({
             enableHighAccuracy: true,
           });
           this.setState({
             lat:JSON.stringify(location.coords.latitude),
             long:JSON.stringify(location.coords.longitude),
           });
       }
 }

Upvotes: 1

Related Questions