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>
);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With