简体   繁体   中英

How to display data after getting complete data from API endpoint in react native?

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: 在此处输入图片说明

您可以在尝试访问它之前确保它已定义,并在加载时呈现一些其他文本。

{this.props.venues ? this.props.venues.data[0].highlight : "Text to display when not loaded"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM