fun joker
fun joker

Reputation: 1727

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: enter image description here

Initially venues is empty array and after fetch the data is filled in see below: enter image description here

Upvotes: 1

Views: 125

Answers (1)

ᴘᴀɴᴀʏɪᴏᴛɪs
ᴘᴀɴᴀʏɪᴏᴛɪs

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

Related Questions