2

I have followed this code from the site "http://carlofontanos.com/user-login-with-wordpress-using-react-native/"

I have done my Login.js like this

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Keyboard
} from 'react-native';
import { AsyncStorage } from 'react-native';
import {Actions} from 'react-native-router-flux';
import { StackNavigator } from 'react-navigation';
export default class LoginForm extends Component<{}> {

  constructor(props){
    super(props)
    this.state={
      userEmail:'',
      userPassword:'',
      validating: false
    }
  }

  login = () =>{
    this.state.validating = true;
    const {userEmail,userPassword} = this.state;
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
    if(userEmail==""){
      //alert("Please enter Email address");
      this.setState({email:'Please enter Email address'})

    }

    else if(reg.test(userEmail) === false)
    {
    //alert("Email is Not Correct");
    this.setState({email:'Email is Not Correct'})
    return false;
      }

    else if(userPassword==""){
    this.setState({email:'Please enter password'})
    }
    else{

    fetch('http://siteURL/wetest/userlogin.php',{
      method:'post',
      header:{
        'Accept': 'application/json',
        'Content-type': 'application/json'
      },
      body:JSON.stringify({
        email: userEmail,
        password: userPassword
      })

    })
    .then((response) => response.json())
     .then((responseJson)=>{
        let data = responseJson.data;
        if (this.saveToStorage(data)){
          this.setState({
            validating: false
          });
          alert("Successfully Login");
          /* Redirect to home page */
          Actions.home()
        } else {
          alert("Wrong Login Details");
        }

     })
     .catch((error)=>{
     console.error(error);
     });
    }


    Keyboard.dismiss();
  }
    render(){
        return(
            <View style={styles.container}>
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Email"
              placeholderTextColor = "#ffffff"
              selectionColor="#fff"
              keyboardType="email-address"
              onChangeText={userEmail => this.setState({userEmail})}
              />
          <TextInput style={styles.inputBox} 
              underlineColorAndroid='rgba(0,0,0,0)' 
              placeholder="Password"
              secureTextEntry={true}
              placeholderTextColor = "#ffffff"
              ref={(input) => this.password = input}
              onChangeText={userPassword => this.setState({userPassword})}
              />  
           <TouchableOpacity style={styles.button} onPress={this.login} >
             <Text style={styles.buttonText}>Login</Text>
           </TouchableOpacity>     
        </View>
            )
    }

  async saveToStorage(userData){
    if (userData) {
      await AsyncStorage.setItem('user', JSON.stringify({
          isLoggedIn: true,
          authToken: userData.auth_token,
          id: userData.user_id,
          name: userData.user_login
        })
      );
      return true;
    }

    return false;
  }
}

And i have done the server site code like this.

*

<?php 
    include 'wp-load.php';
    $json = file_get_contents('php://input');   
    $obj = json_decode($json,true);
    $email = $obj['email'];

    $password = $obj['password'];
$response = array(
    'data'      => array(),
    'msg'       => 'Invalid email or password',
    'status'    => false
);  
    if($obj['email']!=""){  
    $creds = array();
    $creds['user_login'] = $email;
    $creds['user_password'] = $password;
    $creds['remember'] = true;

    $user = wp_signon( $creds, false );

        if ( is_wp_error($user) ){
            echo json_encode('Wrong Details');              
        }
        else{
            $user = get_user_by( 'email', $email );     
            if ( $user ){
                $password_check = wp_check_password( $_POST['password'], $user->user_pass, $user->ID );

                if ( $password_check ){
                    /* Generate a unique auth token */
                    $token = wp_generate_password( 30 );

                    /* Store / Update auth token in the database */
                    if( update_user_meta( $user->ID, 'auth_token', $token ) ){

                        /* Return generated token and user ID*/
                        $response['status'] = true;
                        $response['data'] = array(
                            'auth_token'    =>  $token,
                            'user_id'       =>  $user->ID,
                            'user_login'    =>  $user->user_login
                        );
                        $response['msg'] = 'Successfully Authenticated';
                        //echo json_encode($response);  
                    }
                }
            }           
        }
    }   
    else{
      echo json_encode('try again');
    }

?>

*

If you can see the both code it is written for login and save the data in the device by "async saveToStorage". But for now it giving me the error. The error is "json parse error unexpected eof". You can in the php code, I have tried with return the data by json_encode. That did not work also. Can i get some on this. I want to know where the exact error is ? Thanks in advance.

3
  • Did you check data? is there a valid object in data? When you save data to async storage if the second item is broken, throw this error. Commented Jun 27, 2019 at 7:29
  • How can i test that ? Commented Jun 27, 2019 at 8:12
  • you can check it with alert(JSON.stringify(data)) Commented Jun 27, 2019 at 10:36

2 Answers 2

1

json-parse-error-unexpected-eof it's usually

an error when you are trying to convert non covertable response to json (like html response) into json

for safety I usually convert it first to string using .then(res => res.text()) then console.log() or alert() it to prove the response is convertable to json or not without showing the react-native's red-box message,

if the response is valid json you can convert it by yourself with JSON.parse(responseText)

Sign up to request clarification or add additional context in comments.

Comments

0

For me I got this issue in react once I tried to parse non existed element so I fixed this by checking if the it exists or not

   if (result.data.length >0){
      return JSON.parse(result.data[0].assessment)
    } else {
      return null
    } 

Comments

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.