Aashish Chaubey
Aashish Chaubey

Reputation: 597

React Native: Accessing JSON data

I'm using the fetch API to access the data and it turns out that when accessing this data which I have set in the data source it returns:

Warning: [TypeError: undefined is not an object(evaluating 'response.data.onwardflights')]

I am sure that I've fetched the data correctly as I have seen the data by printing it onto the console.

Here is the code for the same!

'use strict';

import React, {Component} from 'react';
import {StyleSheet, View, Text, ListView, ScrollView} from 'react-native';

const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});

class BusList extends Component {

    constructor() {
    super();
    // const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
    this.state = {
      dataSource: ds.cloneWithRows([]),
      getData: []
    };
  }

    componentDidMount() {
        this.loadJSONData();
    }

    loadJSONData() {
        fetch('api')
          .then((response) => {
            this.setState({getData: response})
            this.setState({dataSource: ds.cloneWithRows(response.data.onwardflights)})
            return response.json()
          })
          .then((responseJSON) => {
                    console.log(responseJSON)
              return this.setState({dataSource: this.state.dataSource.cloneWithRows(responseJSON)});
          })
          .catch((error) => {
            console.warn(error);
          });
    }

    renderRow(rowData) {
        return (
            <View>
                <Text>{rowData.origin}</Text>
            </View>
        );
    }

    render() {
    return (
        <View>
            <ListView
                dataSource = {this.state.dataSource}
                enableEmptySections = {true}
                renderRow = {(rowData) => <Text>{rowData}</Text>}   
            />
        </View>
    );
  }
}

module.exports = BusList;

Any help will be appreciated!

Upvotes: 1

Views: 4218

Answers (1)

Igorsvee
Igorsvee

Reputation: 4201

Of course the response.data.onwardflights will be undefined because you haven't invoked the response.json() prior to reading the data. Invoke the method first, and only then read the data. Please read this article

Upvotes: 0

Related Questions