Assigned response data show [object object] React Native
Solution 1
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
Solution 2
Not related to your question but for me it was quite a pathetic reason why it was showing as [Object Object]. See below difference.
componentWillReceiveProps(nextProps) {
console.log("Data"+nextProps.payload.payloadData); // Display [Object Object]
console.log(nextProps.payload.payloadData); // Display proper list
}
Wahidul Alam
Updated on June 18, 2022Comments
-
Wahidul Alam almost 2 years
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> ); }