0

I am using Laravel and React Native to build a project. I have a post request and which validates data at server side and returns errors. I want to assign the error response in the errors array which has been declared at state. My code are given below :

Laravel:

public function registerUser(Request $request) 
{
    $rules = [
        'username' => 'required', 
        'email' => 'required|email',
        'password' => 'required|min:5'
    ];

    $validator = \Validator::make($request->all(), $rules);

    if ($validator->fails()) {    
        return response()->json(['errors' => $validator->messages()]);
    }

    $user = User::create(request(['username', 'email', 'password']));

    return response()->json('success');
}

React Native:

constructor(props){
        super(props);
        this.state={
            userName:'',
            userEmail:'', 
            userPassword:'',
            errors:[]               
        }
    }

    axios({
        method: 'post',
        url: API_URL+'signup',
        data: {
            username: userName,
            email: userEmail,
            password: userPassword
        }
    })
    .then(function (response) {
        var count = Object.keys(response.data.errors).length;
        if (count > 0) {
            console.log(response.data.errors);
            var newState = new Array(); 
            newState.push(response.data.errors);
            this.setState({
                errors: newState
            })
        }
    })
    .catch(function (error) {
        console.log(error);
    });

It shows me error the below error at console:

undefined is not a function (evaluating 'this.setState({errors: newState})') * app\components\Registration\RegistrationForm.js:51:18 in - node_modules\promise\setimmediate\core.js:37:14 in tryCallOne - node_modules\promise\setimmediate\core.js:123:25 in - ... 10 more stack frames from framework internals

Wahidul Alam
  • 1,216
  • 4
  • 26
  • 56

1 Answers1

0

You need to correctly bind your functions to get the correct this context or use ES6 arrow functions that is already bound to the correct this context

Check the code below

axios({
        method: 'post',
        url: API_URL+'signup',
        data: {
            username: userName,
            email: userEmail,
            password: userPassword
        }
    })
    .then((response) => {
        var count = Object.keys(response.data.errors).length;
        if (count > 0) {
            console.log(response.data.errors);
            var newState = new Array(); 
            newState.push(response.data.errors);
            this.setState({
                errors: newState
            })
        }
    })
    .catch((error) => {
        console.log(error);
    });
Amr Labib
  • 3,995
  • 3
  • 19
  • 31