I am working on a React project in which I am trying to access a key in an object that is an element in an array using an index, but am getting undefined.
The issue seems to be that I am getting an array of objects as props and the index as props as well. When I try to access the id or publicid of the objects in the array using an index from props, I get the error. Below is the simplified version of what I am getting.
Why is this happening and how can I resolve this?
console.log(this.props.images);
// [{id: 1, publicid: "1234" }, {id: 2, publicid: "5678"}]
console.log(this.props.imageIndex)
// 0
console.log(this.props.images[0].publicid)
// 1234
console.log(this.props.images[this.props.imageIndex])
// {id: 1, publicid: "1234" }
console.log(this.props.images[this.props.imageIndex].publicid)
// Cannot read property 'publicid' of undefined
** Updated with more code **
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import * as actions from '../../actions';
class ImageBox extends Component {
handleClick() {
console.log('handleClose:');
}
renderImages() {
console.log(this.props.imageIndex);
// index logs okay
console.log(this.props.images[0]);
// shows correct object in the array
console.log(this.props.images[this.props.imageIndex]);
// again shows correct object in array
console.log(this.props.images[this.props.imageIndex].publicid);
// TypeError: Cannot read property 'publicid' of undefined
return (
<div onClick={this.handleClick.bind(this)}>
<div className="image-box-content">
</div>
</div>
);
}
}
render() {
return (
<div>
{this.renderImages()}
</div>
);
}
}
function mapStateToProps(state) {
return {
auth: state.auth,
successMessage: state.auth.success,
errorMessage: state.auth.error,
};
}
export default connect(mapStateToProps, actions)(ImageBox);
console.logis one after another and there is no any other code in between of them?