Search code examples
javascriptjsonreactjslaravel-5react-native

Assigned response data show [object object] React Native


I am having a problem to iterate the validation errors that i am getting from server side (Laravel). I could get the errors response and assign in state errors array. But when i console.log the state it shows me [obeject object]. So i am unable to iterate the array. Can u guys kindly help ?

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((response) => {
            var count = Object.keys(response.data.errors).length;
            if (count > 0) {
                console.log(response.data);
                var newState = []; 
                newState.push(response.data);
                this.setState({
                    errors: newState
                })
            }

            console.log("error = " + this.state.errors); // console output: error = [object Object]
        })
        .catch((error) => {
            console.log(error);
        });

// inside render function i have done following code to show the validation errors

render() {
    <Errors errors={this.state.errors} />
}

const Errors = (props) => {
    return (
        <View>{props.errors.map((error, i) => <Text key={i}>{error}</Text>)}</View>
    );
}

Solution

  • Shouldn't it be newState.push(response.data.errors) instead of newState.push(response.data) ?

    Also, when printing JSON objects, you need to use JSON.stringify. So console.log(JSON.stringify(this.state.errors)) would have displayed the JSON in readable string format