Last active
May 1, 2020 22:47
-
-
Save renielsalvador/ad88246f13bb83897b5863379045ae32 to your computer and use it in GitHub Desktop.
Simple wrapper for react-native-image-picker
This file contains 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 {useState, useCallback, useMemo} from 'react'; | |
import ImagePicker, {ImagePickerOptions} from 'react-native-image-picker'; | |
type ImageResponse = { | |
uri: any; | |
}; | |
type ImagePickerActions = { | |
showCamera: () => void; | |
showImageLibrary: () => void; | |
}; | |
const handleResponse = (pickerResponse: any): ImageResponse | null => { | |
if (pickerResponse.didCancel) { | |
console.log('User cancelled image picker'); | |
} else if (pickerResponse.error) { | |
console.log('ImagePicker Error: ', pickerResponse.error); | |
} else if (pickerResponse.customButton) { | |
console.log('User tapped custom button: ', pickerResponse.customButton); | |
} else { | |
const source = {uri: pickerResponse.uri}; | |
return source; | |
} | |
return null; | |
}; | |
const launchCamera = (options: ImagePickerOptions): Promise<any> => { | |
return new Promise(resolve => { | |
ImagePicker.launchCamera(options, response => { | |
resolve(handleResponse(response)); | |
}); | |
}); | |
}; | |
const launchImageLibrary = (options: ImagePickerOptions): Promise<any> => { | |
return new Promise(resolve => { | |
ImagePicker.launchImageLibrary(options, response => { | |
resolve(handleResponse(response)); | |
}); | |
}); | |
}; | |
const defaultOptions = {}; | |
/** | |
* Sample Usage: | |
* const [image, pickerActions] = useImagePicker({...options}) | |
* | |
* pickerActions.launchCamera() | |
* @param options | |
*/ | |
const useImagePicker = ( | |
options: ImagePickerOptions = defaultOptions, | |
): [ImageResponse | null, ImagePickerActions] => { | |
const [state, internalSetState] = useState<any>([]); | |
const showCamera = useCallback(() => { | |
launchCamera(options).then(response => { | |
internalSetState(response); | |
}); | |
}, [options]); | |
const showImageLibrary = useCallback(() => { | |
launchImageLibrary(options).then(response => { | |
internalSetState(response); | |
}); | |
}, [options]); | |
const actions = useMemo( | |
() => ({ | |
showCamera, | |
showImageLibrary, | |
}), | |
[showCamera, showImageLibrary], | |
); | |
return [state, actions]; | |
}; | |
export default useImagePicker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment