Home » React-native » React Native – Fetch POST request registration form

React Native – Fetch POST request registration form

Pro Level React-native

React-native Post request API call

In this article, we learn about React-native Fetch POST request registration form

on the last post, we created on registration form UI so we going to use these registrations form here and using Fetch POST request to send data I have created one table as follow  

API code is written in PHP I will write another article for API code

1. Create a project using the following command

 react-native init ApiCallExample

2. Import following in your projects App.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, TextInput, View,
        Dimensions,TouchableOpacity,Button,Alert,Image,
        ImageBackground,StatusBar} from 'react-native';

3. Define constructor

constructor(props) {
   super(props);
    //this.login= this.login.bind(this);
    this.registerCall = this.registerCall.bind(this);
    var {height, width} = Dimensions.get('window');
    this.state = {screenHeight: height, screenWidth: width,
    Usrname: '',
    email : '',
    password: '',
    status: '',
    wholeResult: '',
    baseUrl: 'http://192.168.0.101/android_login_api/' 
  };
}

 

In this constructor, I defined a registerCall method also define username, email, password and baseUrl in react-native state

4. form UI

create form UI with the help of component as follows

return (
     <ImageBackground
       source={require('./image/ic_background.jpg')}
       imageStyle={{resizeMode: 'stretch'}}
       style={{width: '100%', height: '100%'}}>

     <StatusBar
       backgroundColor="#0B7600"
       barStyle="light-content"/>

     <View style={styles.container}>

     <Text style={styles.input}>Registeration</Text>

     <View style={styles.inputContainer}>
       <TextInput style={styles.inputs}
        placeholder="Usrname"
        keyboardType="email-address"
        underlineColorAndroid='transparent'
        onChangeText={(Usrname) => this.setState({Usrname})}/>
     </View>

     <View style={styles.inputContainer}>
       <TextInput style={styles.inputs}
        placeholder="Email"
        keyboardType="email-address"
        underlineColorAndroid='transparent'
        onChangeText={(email) => this.setState({email})}/>
     </View>

     <View style={styles.inputContainer}>

        <TextInput style={styles.inputs}
        placeholder="Password"
        secureTextEntry={true}
        underlineColorAndroid='transparent'
        onChangeText={(password) => this.setState({password})}/>
     </View>

   <TouchableOpacity style={styles.submitButtonText} onPress={() => this.onClickListener('sign_up')}>
    <Text style={styles.signUpText}>Sign up</Text>
   </TouchableOpacity>

  </View>
</ImageBackground>
);

add three TextInputLayout for Username, email, password and create one Sign up button using TouchableOpacity also added onChangeText will call when text change on TextInputLayout and set these value in the setState

 onChangeText={(Usrname) => this.setState({Usrname})}

then add onClickListener to text button view as follows

<TouchableOpacity style={styles.submitButtonText} onPress={() => this.onClickListener('sign_up')}>
   <Text style={styles.signUpText}>Sign up</Text>
</TouchableOpacity>

This is our style sheet

const styles = StyleSheet.create({
   container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
   },
   input: {
      margin: 15,
      fontSize: 40,
      marginBottom : 40,
      color : 'blue'
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 60,
   },
   submitButtonText:{
     color: '#FFFFFF',
     backgroundColor: '#3462FD',
     width:350,
     height:45,
     borderRadius:10,
     justifyContent: 'center',
     alignItems: 'center'
   },
  signUpText:{
     color: '#FFFFFF',
     alignItems: 'center'
  },
  inputContainer: {
     borderBottomColor: '#05C203',
     backgroundColor: '#FFFFFF',
     borderRadius:5,
     borderBottomWidth: 1,
     width:350,
     height:45,
     marginBottom:20,
     flexDirection: 'row',
     alignItems:'center'
  },
  inputs:{
     height:45,
     marginLeft:16,
     borderBottomColor: '#FFFFFF',
     flex:1,
  },
})

Then we write Fetch POST API call as follows

create a method which we had defined in the constructor registerCall in this method first define one variable and assign this to that variable as follows

registerCall(){
  var that = this;
}

then defined your URL below that

registerCall(){
 var that = this;
 var url = that.state.baseUrl + 'register.php';
}

if you want to pass parameters from URL then use that.state.username not this.state.username

after that write fetch post method inside registerCall as follows

 fetch(url,{
     method: 'POST',
     body: JSON.stringify({"name": this.state.Usrname, 
                           "email": this.state.email,
                           "password": this.state.password})
      }).then(function (response) {
          return response.json();
     }).then(function (result) { 
         // console.log(result);
          if(!result.error){
            that.setState({ 
            status: result.error,
            wholeResult: result,
            });
       Alert.alert("User register successfully \n userId: "+that.state.wholeResult.user.uid);
       console.log(that.state.wholeResult.user.uid);
     }else{
       Alert.alert(result.error_msg);
       console.log(result);
    }


}).catch(function (error) {
console.log("-------- error ------- "+error);
alert("result:"+error)
});

In above Fetch POST API call we are passing the body parameters like this

 body: JSON.stringify({"name": this.state.Usrname,
                       "email": this.state.email,
                       "password": this.state.password})

 

After success response, we are setting whole response data in the state that set the complete code for App.js is below

5. App.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, TextInput, View, Dimensions,TouchableOpacity,
Button,Alert,Image,ImageBackground,StatusBar} from 'react-native';


export default class App extends Component<Props> {

constructor(props) {
   super(props);
    //this.login= this.login.bind(this);
    this.registerCall = this.registerCall.bind(this);
    var {height, width} = Dimensions.get('window');
    this.state = {screenHeight: height, screenWidth: width,
                 Usrname: '',
                 email : '',
                 password: '',
                 status: '',
                 wholeResult: '',
                 baseUrl: 'http://192.168.0.101/android_login_api/' };

   }

onClickListener = (viewId) => {
        // Alert.alert(this.state.Usrname+" "+this.state.email+" "+this.state.password , "View_id "+viewId);
        if(this.state.Usrname || this.state.Usrname != " "){
         if(this.state.email){
          if(this.state.password){
              this.registerCall();
           }else{
          Alert.alert("Please enter email");
         }
         }else{
        Alert.alert("Please enter email");
        }
      }else{
    Alert.alert("Please enter username");
   }
 }

registerCall(){
   var that = this;
   var url = that.state.baseUrl + 'register.php';
    console.log("url:"+url);

   fetch(url,{
         method: 'POST',
         body: JSON.stringify({"name": this.state.Usrname, "email": this.state.email,"password": this.state.password})
         }).then(function (response) {
           return response.json();
         }).then(function (result) { 
           // console.log(result);
           if(!result.error){
            that.setState({ status: result.error,
                            wholeResult: result,
                         });
            Alert.alert("User register successfully \n userId: "+that.state.wholeResult.user.uid);
            console.log(that.state.wholeResult.user.uid);
        }else{
         Alert.alert(result.error_msg);
         console.log(result);
   }
}).catch(function (error) {
   console.log("-------- error ------- "+error);
   alert("result:"+error)
 });
}

render() {
  return (
     <ImageBackground
       source={require('./image/ic_background.jpg')}
       imageStyle={{resizeMode: 'stretch'}}
       style={{width: '100%', height: '100%'}}>

    <StatusBar
       backgroundColor="#0B7600"
       barStyle="light-content"/>

   <View style={styles.container}>

   <Text style={styles.input}>Registeration</Text>

   <View style={styles.inputContainer}>
   <TextInput style={styles.inputs}
    placeholder="Usrname"
    keyboardType="email-address"
    underlineColorAndroid='transparent'
    onChangeText={(Usrname) => this.setState({Usrname})}/>
   </View>

   <View style={styles.inputContainer}>
    <TextInput style={styles.inputs}
     placeholder="Email"
     keyboardType="email-address"
     underlineColorAndroid='transparent'
     onChangeText={(email) => this.setState({email})}/>
   </View>

   <View style={styles.inputContainer}>

     <TextInput style={styles.inputs}
      placeholder="Password"
      secureTextEntry={true}
      underlineColorAndroid='transparent'
      onChangeText={(password) => this.setState({password})}/>
   </View>

   <TouchableOpacity style={styles.submitButtonText} onPress={() => this.onClickListener('sign_up')}>
     <Text style={styles.signUpText}>Sign up</Text>
   </TouchableOpacity>

  </View>
  </ImageBackground>
  );
 }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   justifyContent: 'center',
   alignItems: 'center',
  },
  input: {
   margin: 15,
   fontSize: 40,
    marginBottom : 40,
    color : 'blue'
  },
  submitButton: {
   backgroundColor: '#7a42f4',
   padding: 10,
   margin: 15,
   height: 60,
 },
 submitButtonText:{
   color: '#FFFFFF',
   backgroundColor: '#3462FD',
   width:350,
   height:45,
   borderRadius:10,
   justifyContent: 'center',
   alignItems: 'center'
 },
 signUpText:{
   color: '#FFFFFF',
   alignItems: 'center'
 },
 inputContainer: {
   borderBottomColor: '#05C203',
   backgroundColor: '#FFFFFF',
   borderRadius:5,
   borderBottomWidth: 1,
   width:350,
   height:45,
   marginBottom:20,
   flexDirection: 'row',
   alignItems:'center'
 },
 inputs:{
   height:45,
   marginLeft:16,
   borderBottomColor: '#FFFFFF',
   flex:1,
  },
})

make sure after coding complete run following command in the project root folder which builds the project 

react-native run-android

to see the log of API call run following command in the project root folder

react-native log-android

6. Output:

 

React-native Fetch POST request registration form
React-native Fetch POST request registration form

Response

{
 "error": false,
 "error_msg": "",
 "user": {
   "uid": "5bfaeef2962957.31026319",
   "name": "techup",
   "email": "contact@techup.com",
   "created_at": "2018-11-25 13:58:13",
   "updated_at": null
 }
}

enjoy coding…  🙂

Related Posts

10 thoughts on “React Native – Fetch POST request registration form

  1. My brother suggested I might like this website.

    He was entirely right. This post actually made my day.
    You can not imagine simply how much time I had spent for this information! Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *