I'm writing a webapp using React and Redux. I have a Redux action that uses XMLHttpRequest to populate my reducer with data (in array format) from a REST API. I call the action in componentDidMount because thats what the React documentation says is best. When I try to access them in my render function I get a "array[0] is undefined message in the console." But the funny thing is if I define a function that returns JSX using array.map() then it works fine. It just doesn't let me access them individually. Does anyone know why that is?
Code:
import React from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {Row, Col, Grid} from 'react-bootstrap'
import {fetchData} from '../actions'
class DataContainer extends React.Component {
listData(array){
return array.map((element) => {
return(
<Col lg = {3} md = {4} sm = {6} key = {element.id}>
<h3>{element.name}</h3>
<p>{element.description}</p>
</Col>
);
});
}
componentDidMount(){
this.props.getData() //call API
}
render () {
return(
<Grid>
<Row componentClass = "section" id = "non-profits">
{listData(props.data)} //this works
{props.data[0].name} //this doesn't work
</Row>
</Grid>
);
}
}
function mapStateToProps(state){
return{ //maps reducer state to props for use in component
data: state.data //state.data stores the data from the REST API
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({getdata: fetchdata}, dispatch)//fetchData is the redux action that
//calls the REST API
}
export default connect(mapStateToProps, mapDispatchToProps)(DataContainer);
datastate look like?