Tom
Tom

Reputation: 1

Text Input onSubmit while using fetch React Native

I am trying to update my state for nickname and email through textInput and then submit it through a post request to my server. Both keep coming back as undefined. I'm totalling lost as to what I'm doing wrong here.

export default class Add extends Component {
  constructor(props){
    super(props);
    this.state ={ 
      isLoading: true,
      nickname: "",
      email: ""
    }
  }

  static navigationOptions = {
    title: 'Add Contacts',
  };

  componentDidMount(){
        this.setState({
          isLoading: false
        })
  }

  onSubmit = () => {
    console.log('on submit')
    return fetch(`...`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json, text/plain */*',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(this.state)    
        })
        .then((response) => response)
        .then((responseJson) => {
          return responseJson
        })
        .catch((error) => {
          throw error;
        })
  }

  render() {
    const { navigate } = this.props.navigation;
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return(
      <View 
        style={styles.container}
      >
        <Text 
          style={{fontSize:30}}>
          New Contact
        </Text>
            <View>
              <TextInput 
                ref= {(el) => { this.nickname = el; }} 
                onChangeText={(nickname) => this.setState({nickname}, function () {console.log('Nickname updated')})}
                value={this.state.nickname}
              />
              <TextInput 
                value={this.state.email}
                onChangeText={(text) => this.setState({email: text})}   
                />
            </View>
        <Button
          text = {
            <Text 
              style={{color:colors.textColor, textAlign: 'center'}}
              > 
              Save 
            </Text>
          } 
          onPress= { () => {
              this.onSubmit()
              navigate('Home')
           }
          }
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    marginTop: 20,
    alignItems: 'center',
    justifyContent: 'center',
  }
});

Upvotes: 0

Views: 930

Answers (1)

David Hellsing
David Hellsing

Reputation: 108500

.then((response) => response)

Should be:

.then((response) => response.json())

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Making_fetch_requests

Upvotes: 1

Related Questions