I am new to React and Axios. I want to GET customer data, yet when their address is empty, an Error appeared
"TypeError: Cannot read property 'street' of undefined."
When customer has address, everything works. Is there any way I can make this work without touching the BackEnd?
class Account extends Component {
constructor(props) {
super(props);
this.state = {
orders: []
};
componentDidMount() {
axios.get(`https://api.mysite.com/customer`)
.then(res => {
const orders = res.data;
this.setState({ orders });
console.log(orders);
})
}
render() {
return (
<div className="input left">
{this.state.orders.map(order => <Input className="name" type="text" readOnly value={order.name} />)}
{this.state.orders.map(order => <Input className="email" type="text" readOnly value={order.email} />)}
{this.state.orders.map(order => <Input className="password" type="text" readOnly value="*******" />)}
{this.state.orders.map(order => <Input className="address" type="textarea" readOnly value={order.address[0].street} />)}
{this.state.orders.map(order => <Input className="phone" type="text" readOnly value={order.address[0].phone} />)}
</div>
);
}
}
Sorry if the name is confusing, I just copied it from my /order page
Here is the console.log(order) from the WORKING account
0:
address: Array(1)
0:
city: "Jakarta Utara"
country: "Indonesia"
created_at: "2019-05-21 10:54:19"
customer_id: "c8ca7ce0-7bb6-11e9-90f8-e1b44f49dcc3"
id: "c8cc3910-7bb6-11e9-b13b-537042a9805b"
name: "fendi"
phone: "0812308123"
postal_code: "14420"
province: "DKI Jakarta"
street: "test"
updated_at: "2019-05-21 10:54:19"
__proto__: Object
length: 1
__proto__: Array(0)
created_at: "2019-05-21 10:54:19"
email: "[email protected]"
email_verified_at: null
id: "c8ca7ce0-7bb6-11e9-90f8-e1b44f49dcc3"
name: "test"
role_id: "a022e290-7bb6-11e9-9fb6-09e2f5236d0a"
updated_at: "2019-05-21 10:54:19"
Here is the console.log(order) from the NOT WORKING account
0:
address: Array(0)
length: 0
__proto__: Array(0)
created_at: "2019-05-21 10:53:11"
email: "[email protected]"
email_verified_at: "2019-05-21 10:53:11"
id: "a02279a0-7bb6-11e9-8711-515da07aadda"
name: "Alisha Stamm"
role_id: "a0156ca0-7bb6-11e9-8ba3-43dcab891f96"
updated_at: "2019-05-21 10:53:11"
As can be seen, the account that throws an error doesnt have any address (like street name) and I called .address.street which is undefined
Please help, thank you!