2
votes

I'm trying to take a picture using Expo's Camera object.

Using Expo 25.0.0 and React-native 0.52.0

A simple sample code of the problem I'm experiencing is below:

import React from 'react';
import { Camera } from 'expo';
import { Text, View, TouchableOpacity } from 'react-native';

export default class App extends React.Component {
    async press() {
        console.log('Button Pressed');
        if (this.camera) {
            console.log('Taking photo');
            let photo = await this.camera.takePictureAsync();
            console.log(photo);
        }
    }

    render() {
        return (
            <Camera
                style={{ flex: 1 }}
                ref={ (ref) => {this.camera = ref} }
            >
                <View style={{ flex: 1 }}></View>
                <TouchableOpacity
                    style={{ flex: 0, backgroundColor: 'red' }}
                    onPress={this.press}
                >
                    <Text>Touch Me</Text>
                </TouchableOpacity>
            </Camera>
        );
    }
}

What happens is:

  • Camera view displays
  • press() callback is called, but not photo is taken
  • If I remove the if (this.camera) check, I get a warning, [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.camera.takePictureAsync')]

It seems to me that the reference to the camera object is never made, but I can't seem to figure out why this is the case or what I'm doing differently from the documentation.

1

1 Answers

3
votes

Bind the press callback or use arrow functions.

Replace onPress={this.press} with onPress={this.press.bind(this)}