0

I want to pass a username and password to an API. My code allows a user to login and the API can check or reject the request depending on whether or not the user exists.

However, I want to take the response and display the username on the next screen. How do I approach this?

Here is the response back (if the login is successful):

{
  "data": {
    "user": {
      "name": "Test One",
      "email": "[email protected]",
      "username": "testuser1",
      "token": "3uio42h34b398r2h",
      "avatar": "/images/default.png"
    }
  }
}

Here is my source code:

import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button
} from "react-native";

export default class LoginForm extends Component<{}> {
  constructor(props) {
    super(props);
    this._onLogInPressed = this._onLogInPressed.bind(this);
    this._response_recognizer = this._response_recognizer.bind(this);
    this.state = {
      phone_number: "",
      password: "",
      data: {}
    };
  }
  _response_recognizer(data: string) {}

  _onLogInPressed = () => {
    var data = {
      phone_number: this.state.phone_number,
      password: this.state.password
    };

    fetch("http://192.168.1.12:5000/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email: this.state.email
      })
    })
      .then(response => response.json())

      .then(res => {
        console.log(res);

        if (res.status == 200) {
          this.props.navigation.navigate("Login");
          alert("Check your email for a password reset link!");
        } else if (res.status != 200) {
          alert("Email does not exist in our system.");
        }
      })
      .done();
  };

  render() {
    return (
      <View style={styles.flow}>
        <Text style={styles.text}>phone number:</Text>
        <TextInput
          keyboardType="numeric"
          style={styles.input}
          ref="phone_number"
          onChangeText={phone_number => this.setState({ phone_number })}
          maxLengt={11}
          value={this.state.phone_number}
        />
        <Text style={styles.text}>password:</Text>
        <TextInput
          style={styles.input}
          secureTextEntry={true}
          ref="password"
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button
          style={styles.button}
          onPress={this._onLogInPressed}
          title="login"
        />
      </View>
    );
  }
}
4
  • 1
    You could e.g. do the request in the componentDidMount hook of a component, and then use setState to set the response data in state. Commented Aug 1, 2018 at 21:59
  • @Tholle i added my source code. Could you elaborate on what you mean? Commented Aug 1, 2018 at 22:25
  • You could pass the parameters to the next scree, as outlined here. Commented Aug 1, 2018 at 22:30
  • @Tholle I think that would only pass the response values no? My console outputs the JSON code block above if login is successful. How do I take that console output, access the username JSON value and display it? Commented Aug 1, 2018 at 22:42

1 Answer 1

1
/* --------- Define 'name' in state ---------*/

 state = {
    name: ''
 }

/*------- if you will get success response then write this  -------*/ 

LoginAPICall = () => {
fetch(‘URL’, {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
},
body: JSON.stringify({
  Email: this.state.email,
  Password: this.state.password
})
}).then((response) => response.json())
  .then((responseJson) => {
 if(responseJson.statuscode == 1) {
  this.props.navigation.navigate(‘Login’,{
            NAME : responseJson['data']['user'].name
    });
  alert("Check your email for a password reset link!");      
} else {
  Alert.alert(responseJson.message);
}
}).catch((error) => {
  console.error(error);
});
}


/*--------- in next activity controller write below lines ---------*/

    constructor(){
    super();
    this.state = {
         User_Name : '',
    }
}

componentDidMount(){
    this.setState({
        User_Name: this.props.navigation.state.params.NAME,
    })
}

render () {
  alert (this.state.User_Name);
  return (
    <View>
        <Text>Hello</Text>
    </View>
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

I got the error: responseJson is not defined. How do I approach that error?
I ended up doing response.json but I'm not sure if that's correct. Now i'm getting the error "Cannot read property 'data' of undefined'. How do i deal with that?
I got the code to work. What we have to do is reference res not responsejson:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.