From fe82863bbd0fe355db3fa67968d0893320002fac Mon Sep 17 00:00:00 2001 From: Leo Lin Date: Fri, 28 Sep 2018 11:07:15 +0800 Subject: [PATCH] add error handling for await --- index.js | 71 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/index.js b/index.js index 4548646..80b9c67 100644 --- a/index.js +++ b/index.js @@ -55,9 +55,9 @@ export default class PhotoUpload extends React.Component { ImagePicker.showImagePicker(this.options, async response => { this.setState({buttonDisabled: false}) - let rotation = 0 + let rotation = 0 const {originalRotation} = response - + if (this.props.onResponse) this.props.onResponse(response) @@ -76,42 +76,45 @@ export default class PhotoUpload extends React.Component { } let { maxHeight, maxWidth, quality, format } = this.state - + //Determining rotation param - if ( originalRotation === 90) { - rotation = 90 - } else if (originalRotation === 180) { - //For a few images rotation is 180. - rotation = -180 + if ( originalRotation === 90) { + rotation = 90 + } else if (originalRotation === 180) { + //For a few images rotation is 180. + rotation = -180 } else if ( originalRotation === 270 ) { //When taking images with the front camera (selfie), the rotation is 270. - rotation = -90 + rotation = -90 + } + try { // resize image + const resizedImageUri = await ImageResizer.createResizedImage( + `data:image/jpeg;base64,${response.data}`, + maxHeight, + maxWidth, + format, + quality, + rotation + ) + + if (this.props.onResizedImageUri) this.props.onResizedImageUri(resizedImageUri) + + const filePath = Platform.OS === 'android' && resizedImageUri.uri.replace + ? resizedImageUri.uri.replace('file:/data', '/data') + : resizedImageUri.uri + + // convert image back to base64 string + const photoData = await RNFS.readFile(filePath, 'base64') + let source = {uri: resizedImageUri.uri} + this.setState({ + avatarSource: source + }) + + // handle photo in props functions as data string + if (this.props.onPhotoSelect) this.props.onPhotoSelect(photoData) + } catch (e) { + if (this.props.onError) this.props.onError(e) } - // resize image - const resizedImageUri = await ImageResizer.createResizedImage( - `data:image/jpeg;base64,${response.data}`, - maxHeight, - maxWidth, - format, - quality, - rotation - ) - - if (this.props.onResizedImageUri) this.props.onResizedImageUri(resizedImageUri) - - const filePath = Platform.OS === 'android' && resizedImageUri.uri.replace - ? resizedImageUri.uri.replace('file:/data', '/data') - : resizedImageUri.uri - - // convert image back to base64 string - const photoData = await RNFS.readFile(filePath, 'base64') - let source = { uri: resizedImageUri.uri } - this.setState({ - avatarSource: source - }) - - // handle photo in props functions as data string - if (this.props.onPhotoSelect) this.props.onPhotoSelect(photoData) }) }