bobby747
bobby747

Reputation: 13

React Native json object does not show in ListView

I'm new to RN and am trying to show a ListView populated with data from a json array, If I use a simple array then I can see the data however when I use the json array as shown in the code I don't see anything populated when I run the emulator. Is there a specific way to handle the json in my example below to show it in the ListView:

class FetchExample extends Component {

  constructor(props) {
    super(props);
    // Initialize the hardcoded test data - to be replaced by JOSN fetch
    let data = {"Vehicles":[[
      {"vehicle_make": "Toyota", 
      "vehicle_model": "Camry", 
      "vehicle_year": "2015", 
      "vehicle_price_range": "$$ (10-30)", 
      "car_id": 1127, 
      "vehicle_color": "Black", 
      "vehicle_car_accidents": "No", 
      "vehicle_no_owners": "1", 
      "car_vehicle_location": "Lot", 
      "vehicle_city_location": "L.A", 
      "vehicle_mileage": 10864, 
      "vehicle_vin": 1234, 
      "vehicle_off_lease": "Yes", 
      "vehicle_state": "CA"
    }]]};
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(data)
    };
    console.log(data);
  }
  render() {
    return (
      <View style={{paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData.Vehicles}</Text>}
        />
      </View>
    );
  }
}

Upvotes: 1

Views: 1561

Answers (1)

vgrafe
vgrafe

Reputation: 1350

If I refer to the docs, It looks like your data should be an array rather than an object. can you try with the following?

let data = [
  {"vehicle_make": "Toyota", 
  "vehicle_model": "Camry", 
  "vehicle_year": "2015", 
  "vehicle_price_range": "$$ (10-30)", 
  "car_id": 1127, 
  "vehicle_color": "Black", 
  "vehicle_car_accidents": "No", 
  "vehicle_no_owners": "1", 
  "car_vehicle_location": "Lot", 
  "vehicle_city_location": "L.A", 
  "vehicle_mileage": 10864, 
  "vehicle_vin": 1234, 
  "vehicle_off_lease": "Yes", 
  "vehicle_state": "CA"
}];

edit: you can instead replace

dataSource: ds.cloneWithRows(data)

with

dataSource: ds.cloneWithRows(data.Vehicles[0])

but I'd suggest you flatten your data as much as you can.

edit 2: The render method also needs modification. try to change renderRow to the following:

renderRow={(rowData) => <Text>{rowData.vehicle_make}</Text>}

Upvotes: 3

Related Questions