Home > OS >  Possible unhandled promise Rejection (id:0) React Native
Possible unhandled promise Rejection (id:0) React Native

Time:08-09

Having error, dunno what's wrong in here. Any idea? I need to get longitude and latitude. kindly tell me if there are any other good approach with Expo created react native project. thanks!

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Location, Permissions } from 'expo';
import React from 'react';

export default class App extends React.Component{

  state = {
    location: {},
    erroMessage: '',
  }

  componentWillMount(){
    this._getLocation();
  }

  _getLocation = async () => {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if(status !== 'granted'){
      console.log('PERMISSION NOT GRANTED!');

      this.setState({
        erroMessage: 'PERMISSIN NOT GRANTED'
      })
    }

    const location = await Location.getCurrentPositionAsync();

    this.setState({
      location,
    });

  };

  render () {
    return (
      <View style={styles.container}>
        <Text>{JSON.stringify(this.state.location)}</Text>
        <StatusBar style="auto" />
      </View>
    );
  }
}

CodePudding user response:

You don't have any error handling for either Promises that come from Permissions.askAsync and Location.getCurrentPositionAsync. Wrap the awaited functions in a try / catch block and handle any errors from the error block.

_getLocation = async () => {
  try {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if(status !== 'granted'){
      console.log('PERMISSION NOT GRANTED!');

      this.setState({
        erroMessage: 'PERMISSIN NOT GRANTED'
      });
    }

    const location = await Location.getCurrentPositionAsync();

    this.setState({
      location,
    });
  } catch (error) {
    // Handle any errors here.
  }
};

CodePudding user response:

You need to add else condition as well. If permission is not granted stop execution or ask again for permissions.

_getLocation = async () => {
try {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status !== 'granted') {
        console.log('PERMISSION NOT GRANTED!');

        this.setState({
            erroMessage: 'PERMISSIN NOT GRANTED',
        });
    } else {
        const location = await Location.getCurrentPositionAsync();

        this.setState({
            location,
        });
    }
} catch (error) {
    // Handle any errors here.
}

};

  • Related