Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 29428

Why am I getting React Native [TypeError: undefined is not an object (evaluating '_this2.setState') error in when changing this.state after biding

$
0
0

I'm a little new to react and I cannot figure out why I get the [TypeError: undefined is not an object (evaluating '_this2.setState')] error when calling

.then(r => {this.setState({ photos: r.edges },() =>
console.log("state after _getPhotosFromDevice: " + JSON.stringify(this.state))

Even after binding the method in the constructor

this._requestCameraPermission = this._requestCameraPermission.bind(this)

I know it has something to do with the 'this' context not being available to it but I can't figure out why. Does it have something to do with the way JS handles async classes? I'm out of ideas here.

Full code

'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Button
} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import CameraRoll from '@react-native-community/cameraroll';
import Moment from 'moment';

import PermissionsAndroid, {
  NotificationsResponse,
  Permission,
  PERMISSIONS,
  PermissionStatus,
  RESULTS,
} from 'react-native-permissions';

export default class TaskForm extends Component<Props> {

constructor(props) {
    super(props);
    this._requestCameraPermission = this._requestCameraPermission.bind(this)
    this._getPhotosFromDevice = this._getPhotosFromDevice.bind(this)
    this._requestCameraPermission = this._requestCameraPermission.bind(this)
    this.state = {
        task: '',
        type: '',
        stuff: '',
        status: '',
        dueDate: new Moment().format('MM/DD/YYYY'),
        subject: '',
        showDatePicker: false
    };
  }

 submit = (form) => {
      alert( 'task: ' + form.task)

        console.log("form.due date" + JSON.stringify(form.dueDate))

     var newItem = {
         id : Math.floor(Math.random() * 1000000),
         task : form.task,
         status : form.status,
         type : form.type,
         dueDate : form.dueDate,
         stuff : form.stuff,
         subject : [form.subject]
    };

      this.props.navigation.state.params.onGoBack(newItem);
      this.props.navigation.goBack();

   }


    _addPictureToState(r){

        this.state.setState({ photos: r.edges })

    }

    _getPhotosFromDevice = () =>{
            this._requestCameraPermission()
                .then(function (didGetPermission: boolean) {
                console.log("reqCamera ret : " + didGetPermission)
                if (didGetPermission) {

                     CameraRoll.getPhotos({
                        first: 20,
                        assetType: 'Photos'
                      })
                      .then(r => {this.setState({ photos: r.edges },() =>

                                console.log("state after _getPhotosFromDevice: " + JSON.stringify(this.state))

                            )
                      })
                      .catch((err) => {
                        console.info(err);
                      })

                }else{
                     alert("Oh no no permissions!")
                }
            });

    }

    async _requestCameraPermission(){

        console.log("entering _requestCameraPermission")
        var perm = await PermissionsAndroid.request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE,{

        title: 'Hey you need to give us contacts permissions!',
         message: 'We need to read your contacts so we can sell them to advertisers.'
        });
        console.log("requesting permission : " + perm);
        return perm === RESULTS.GRANTED;

    }

 render(){
    var date = this.state.dueDate
    return(
       <View style = {styles.container}><TextInput
             style = {styles.input}
             placeholder="Task Number!"
             onChangeText={(task) => this.setState({task})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Type!"
             onChangeText={(type) => this.setState({type})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Stuff!"
             onChangeText={(stuff) => this.setState({stuff})}
             value={this.state.text}
           /><TextInput
             style = {styles.input}
             placeholder="Subject!"
             onChangeText={(subject) => this.setState({subject})}
             value={this.state.text}
           /><TextInput
                style = {styles.input}
                placeholder="Status!"
                onChangeText={(status) => this.setState({status})}
                value={this.state.text}
              /><TouchableOpacity
             style = {styles.input}
             onPress={() => {
                this.setState({showDatePicker: true})
                console.log("in text area: " + JSON.stringify(this.state));
              }}><Text style = {styles.input} >{this.state.dueDate.toString()}</Text></TouchableOpacity><View>
               { this.state.showDatePicker &&(<DateTimePicker
                    value={new Date()}
                    mode='date'
                    display='default'
                    onChange={ (event, selectedDate)  => {
                        this.setState({showDatePicker: false, dueDate:Moment(selectedDate).format('MM/DD/YYYY')},()=>console.log("afterOnChange: " + JSON.stringify(this.state)))
                     }} />
                )}</View><Button
                 title='View Photos'
                 onPress={ () => this._getPhotosFromDevice()}
               /><TouchableOpacity
              style = {styles.submitButton}
              onPress = {
                 () => this.submit(this.state)
              }><Text style = {styles.submitButtonText}> Submit </Text></TouchableOpacity></View>
    )
 }

}

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 1,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})

Viewing all articles
Browse latest Browse all 29428

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>