Reputation: 1727
I am fetching data from API endpoint. I have made action and reducer for VenueList.js
venueAction.js:
import { FETCH_VENUES } from './types';
import axios from 'axios';
export const fetchVenues = () => dispatch => {
axios.get(`API_ENDPOINT`)
.then( venues =>
dispatch({
type: FETCH_VENUES,
payload: venues
})
)
.catch( error => {
console.log(error);
});
};
venueReducer.js:
import { FETCH_VENUES } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_VENUES:
return {
...state,
items: action.payload
};
default:
return state;
}
}
VenueList.js:
import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import { fetchVenues } from '../actions/venueAction';
class VenueList extends Component {
componentWillMount (){
this.props.fetchVenues();
}
render() {
// if(this.props.venues.data){
console.log(this.props.venues.data[0].highlight)
// }
return (
<View style={styles.container}>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
const mapStateToProps = state => ({
venues: state.venues.items
})
export default connect (mapStateToProps, { fetchVenues })(VenueList);
If I uncomment the if statement in VenueList.js then it shows the this.props.venues.data[0].highlight
data but if there is no if statement then it throws error. How can I display data after getting the data from API endpoint. Initially during fetch venues
are undefined and after 1 sec the data is filled in using api endpoint. So if I want to display
<Text>{this.props.venues.data[0].highlight}</Text>
it throws error Do I need to add if statements at each sections. How can I overcome this issue ?
Screenshots:
if I comment the if statement:
Initially venues is empty array and after fetch the data is filled in see below:
Upvotes: 1
Views: 125
Reputation: 7529
You can ensure it's defined before trying to access it, and render some other text while it's loading.
{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}
Upvotes: 1