2

I am using react-native and parse server. I'm implementing user registration, but this error appears:

undefined is not object (evaluating 'this.state.username')

Should not the state be read across the class?

import React, {Component} from 'react';
import {Container, Content, Form, Item, Input, Button, Text} from 'native-base';
var Parse = require('parse/react-native');

export default class Singup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
  }

  Buttonpress() {
    Parse.initialize("APPLICATION_ID");
    Parse.serverURL = 'http://***.***.**.**:1337/parse'

    var user = new Parse.User();
    user.set("username", this.state.username);
    user.set("password", this.state.password);

    user.signUp(null, {
      success: function(user) {
        console.warn("YES");
      },
      error: function(user, error) {
        // Show the error message somewhere and let the user try again.
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }

  render() {
    return (
      <Container>
        <Content>
          <Form>
            <Item>
              <Input
                placeholder="Username"
                onChangeText={(text) => this.setState({username: text})}
                value = {this.state.username}/>
            </Item>
            <Item last>
              <Input
                placeholder="Password"
                onChangeText={(text) => this.setState({password: text})}
                value = {this.state.password}/>
            </Item>
          </Form>
          <Button
            block
            onPress={this.Buttonpress}>
            <Text>Inscrever-se</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

Translated automatically.

Cláudio Júlio
  • 365
  • 4
  • 16

1 Answers1

4

Binding of your function should help you

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
    this.Buttonpress = this.Buttonpress.bind(this);
  }

Here is the reference: https://facebook.github.io/react/docs/react-without-es6.html#autobinding

Cláudio Júlio
  • 365
  • 4
  • 16
Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
  • this question has multiple duplicates on StackOverflow, please consider marking it as a duplicate or providing an appropriate link rather than answering it, – Shubham Khatri Jul 21 '17 at 17:02
  • Thank you! Can you give me a reference of why I need this? I would like to understand. – Cláudio Júlio Jul 21 '17 at 17:10
  • [This one](https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56) is about binding variants. [Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Andrii Starusiev Jul 21 '17 at 18:13