Created
          May 27, 2020 12:55 
        
      - 
      
 - 
        
Save ivanstnsk/4ff5bd5f1fd3c7294ebe5c365fdf48a4 to your computer and use it in GitHub Desktop.  
    use Android Permissions hook React Native in Typescript
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import { useEffect, useState } from 'react'; | |
| import { PermissionsAndroid } from 'react-native'; | |
| type THook = [boolean, boolean]; | |
| interface PermissionsAndroidResponse { | |
| [key: string]: string; | |
| } | |
| const PERMISSIONS_REQUEST = [ | |
| PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, | |
| PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, | |
| ]; | |
| const isAllGranted = (res: PermissionsAndroidResponse) => { | |
| return PERMISSIONS_REQUEST.every((permission) => { | |
| return res[permission] === PermissionsAndroid.RESULTS.GRANTED; | |
| }); | |
| } | |
| export const useAndroidPermissions = (): THook => { | |
| const [granted, setGranted] = useState(false); | |
| const [waiting, setWaiting] = useState(true); | |
| const doRequest = async () => { | |
| let granted = false; | |
| try { | |
| const res = await PermissionsAndroid.requestMultiple(PERMISSIONS_REQUEST); | |
| granted = isAllGranted(res); | |
| } catch (err) { | |
| console.warn(err); | |
| } | |
| setWaiting(false); | |
| setGranted(granted); | |
| } | |
| useEffect(() => { | |
| doRequest(); | |
| }, []); | |
| return [waiting, granted]; | |
| }; | |
| // Example of usage | |
| // const [waitingPerm, grantedPerm] = useAndroidPermissions(); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Your work is valuable! Thanks for posting this online!