0

So all I want is an image picker in React Native that creates the image on the server and a database entry as well. I need to use the expo-image-picker package.

I can already successfully upload images with the following code:

Profile.js:

import * as ImagePicker from 'expo-image-picker';
...
class ProfileScreen extends React.Component {
...
_pickImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1
  });

  if (!result.cancelled) {
  this.setState({ image: result.uri });
  }
};
...
<View>
  <Button
    title="Pick an image from camera roll"
    onPress={this._pickImage}
  />
  {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>

This works without any issue.

Now I additionally want to create a database entry with the newly created file. But I have no idea how to combine these both.

Here is how I was able to create the database image entry without the expo-image-picker package (but at the end I need it with that package):

Profile.js

const UPLOAD_FILE = gql`
  mutation uploadFile($file: Upload!) {
    uploadFile(file: $file)
  }
`;
...
<Mutation mutation={ UPLOAD_FILE }>
  { 
    uploadFile => (
      <Input
        type="text"
        required
        onChange={({ target: { validity, files: [file] } }) =>
          validity.valid && uploadFile({ variables: { file } })
        }
      />
    )
  }
</Mutation>

And the uploadFile call is in mutation.js file. But this is shown here as it is not important (because the database entry creation works perfectly with that code).

So to conclude, the question is now, how to mix both code snippets, so that it works with the expo-image-picker package?

My idea was to add the uploadFile call in the _pickImage function maybe? Or would it be better to call the mutation on the onPress={this._pickImage} maybe with a combination like onPress={this._pickImage && uploadFile({ variables: { file } })}?

What is the best practice in general?

kwoxer
  • 3,167
  • 3
  • 35
  • 51

0 Answers0