skip to Main Content

I’m having an issue with posting data to an express REST API I have using fetch in my react-native app. Here’s my code:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Button from 'react-native-button';
import DeviceInfo from 'react-native-device-info'

export default class ReliefMobile extends Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {
      currentLocation: {latitude: 40.6391, longitude: 10.9969},
      name: 'Some dumb name',
      description: 'Some dumb description',
      deviceId: DeviceInfo.getUniqueID()
    }
  }

  addData() {
    fetch('http://localhost:3000/api/effort/add', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: this.state.name,
        description: this.state.description,
        deviceId: this.state.deviceId,
        currentLocation: this.state.currentLocation
      })
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native
        </Text>
        <Text style={styles.instructions}>
          Your device ID is {DeviceInfo.getUniqueID()}
        </Text>
        <Text style={styles.instructions}>
        Effort Name: {this.state.name}
        </Text>
        <Text style={styles.instructions}>
        Effort Description: {this.state.description}
        </Text>
        <Text style={styles.instructions}>
        Location: {this.state.currentLocation.latitude}, {this.state.currentLocation.longitude}
        </Text>
        <Button onPress={this.addData}>Add data</Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ReliefMobile', () => ReliefMobile);

When I try to press my button to call the addData function, I get this error: undefined is not an object (evaluating this.state.name).

On load of the app, my state variables seem to be loading just fine into the <Text/> areas:

Imgur

But when I submit this is what shows:
Imgur

When I change the body of the fetch to be something like

body: JSON.stringify({name: 'some name', description: 'some description'})

It works fine. So I thought that the value of this might not be the same from within the fetch function, so at the top of addData() I did something like let that = this; and set all my state variables to that.state.name, etc but that still didn’t work.

3

Answers


  1. React handlers are not automatically bound to the element/class they are in.

    <Button onPress={this.addData.bind(this)}>Add data</Button>
    

    https://facebook.github.io/react/docs/handling-events.html

    Excerpt from above link

    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
    
    Login or Signup to reply.
  2. Probably you need to bind the context. In your onClick method add something like this: onClick={this.addData.bind(this)}. This way the method can have access to the state object.

    Login or Signup to reply.
  3. You should bind in your constructor not in the render function. In your constructor, just add:

    this.addData = this.addDate.bind(this);

    You can also use ES6 as another alternative:

    addData = () => { ... }

    That will work to as documented here: https://babeljs.io/blog/2015/06/07/react-on-es6-plus under the arrow function section.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search