Home > Enterprise >  How to properly use axios to post form data to a php REST API using React Native Context API?
How to properly use axios to post form data to a php REST API using React Native Context API?

Time:01-08

I am trying to use a react native form to post user registration data to a PHP API. I have tested the API using POSTMAN and it accepts the data and sends back proper success and error responses.

However, the react native form fails to send the data probably because I am doing something NOT right in my code:

Here is the relevant method in MyContext.js file:

registerUser = async (user) => {
    // Sending the user registration request
    const register = await Axios.post('apiRegister.php',{
        username:user.username,
        fname:user.fname,
        lname:user.lname,
        email:user.email,
        password:user.password 
    });

    return register.data;
}

And given below the complete code of the register screen in the react native project:

import React, {useContext, useState} from 'react';
import { Text, View, StyleSheet, TextInput, Button, Alert } from 'react-native';
import {MyContext} from '../contexts/MyContext';
import Constants from 'expo-constants';
import Login from './Login';


export default function Register({navigation}) {
  const registerUser = useContext(MyContext);
  const initialState = {
    userInfo:{
        username:'',
        fname:'',
        lname:'',
        email:'',
        password:'',
    },
    errorMsg:'',
    successMsg:'',
  }
  const [state,setState] = useState(initialState);

  // On Submit the Registration Form
  const submitForm = async (event) => {
    event.preventDefault();
    const data = await registerUser(state.userInfo);
    if(data.success){
        setState({
            ...initialState,
            successMsg:data.message,
        });
    }
    else{
        setState({
            ...state,
            successMsg:'',
            errorMsg:data.message
        });
    }
}


const onChangeValue = (e) => {
  setState({
      ...state,
      userInfo:{
          ...state.userInfo,
          [e.target.name]:e.target.value
      }
  });
}

// Show Message on Success or Error
let successMsg = '';
let errorMsg = '';
if(state.errorMsg){
    errorMsg = <View>{state.errorMsg}</View>;
  }
  if(state.successMsg){
    successMsg = <View>{state.successMsg}</View>;
  }


  return(
    <View style={styles.container}>
        <Text style={styles.heading1}>Sign Up</Text>
        <form onSubmit={submitForm} noValidate>
            <View style={styles.inputTextWrapper}>
                <label>Username</label>
                <input name="username" type="text" required placeholder="Username" value={state.userInfo.username} onChange={onChangeValue} />                
            </View>
            <View style={styles.inputTextWrapper}>
                <label>First name</label>
                <input name="fname" type="text" required placeholder="First name" value={state.userInfo.fname} onChange={onChangeValue} />                
            </View>
            <View style={styles.inputTextWrapper}>
                <label>Last name</label>
                <input name="lname" type="text" required placeholder="Last name" value={state.userInfo.lname} onChange={onChangeValue} />                
            </View>
            <View style={styles.inputTextWrapper}>
                <label>Email</label>
                <input name="email" type="email" required placeholder="Email" value={state.userInfo.email} onChange={onChangeValue} />
                
            </View>
            <View style={styles.inputTextWrapper}>
                <label>Password</label>
                <input name="password" required type="password" value={state.userInfo.password} onChange={onChangeValue} placeholder="Password"/>
            </View>
            <View>
            {errorMsg}
            {successMsg}
            </View>
            <View style={styles.btnContainer}>
                <Button
                    title="Register"
                    onPress={submitForm}
                />
            </View>
            <Text>{'\n'}</Text>
        </form>
        <View style={styles.btnContainer}>
            
            <Button
                title="Login"
                onPress={() => navigation.navigate("Login")}
            />            
        </View>
    </View>
);


}

I am hoping if someone could please have a look at this code and help with correct it or point me to a resource where I could learn to make use of react native forms, Axios and Context API to post and get data via PHP APIs. Thanks in anticipation.

CodePudding user response:

const registerUser = async () => {
    const data = {
    username:user.username,
    fname:user.fname,
    lname:user.lname,
    email:user.email,
    password:user.password 
    };

    const config = {
      method: 'post',
      data: data,
      url: 'Write here your api URL example https://facebook.com/feed',
    };
    axios(config)
      .then(async (response) => {
        console.log('response',response);
        //you can use here a state to set your data response
      })
      .catch((error) => {
        console.log(`error`, error.response);
      });
  };
  •  Tags:  
  • Related