Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Opening an alert function when permission is not 'granted'

In my code, you can see it starts by asking for the users location permission. When granted, it logs and displays the users latitude and longitude.

I am trying to have an alert pop up when the user declines this permission. I thought it would be as simple as what I have implemented in the code below but obviously something is wrong. I am calling my permissionAlert function in my if statement when status != granted.

I have included the code below as well as a snack example here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for any insight at all.

export default function App() {
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  

  const permissionAlert = () => {
     Alert.alert(
      'You did not allow location permissions',
      [
        {text: 'Yes', onPress: () => console.log('Yes button clicked')},
        {text: 'No', onPress: () => console.log('No button clicked'), style: 'cancel'},
      ],
      { 
        cancelable: true 
      }
    );
  }

  useEffect(() => {
    (async () => {
      
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        permissionAlert();
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLatitude(location.coords.latitude)
      setLongitude(location.coords.longitude);
    })();
  }, []);


  console.warn("latitude: ", latitude);
  console.warn("longitude: ", longitude);
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{latitude}</Text>
      <Text style={styles.paragraph}>{longitude}</Text>
    </View>
  );
}

>Solution :

Looks like you’re not using the Alert API correctly.

Alerts 2nd argument is description, but you are trying to pass in an array of actions, which should be 3rd argument instead.

So it should be something like this

 Alert.alert(
     'Permission denined',
      'You did not allow location permissions',
      [
        {text: 'Yes', onPress: () => console.log('Yes button clicked')},
        {text: 'No', onPress: () => console.log('No button clicked'), style: 'cancel'},
      ],
      { 
        cancelable: true 
      }
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading