Veer3383
Veer3383

Reputation: 1825

How to populate datasource for listview using api response in react native?

My Api returns me a response exactly like the const "devices" defined below. If i don't call the api, i am getting the listview properly populated with single row of data, but if i populate the datasource using Api response, i am getting empty 160 rows.

Whats wrong with my setState?

    const devices = [
        {
            "DeviceID": 4,
            "DeviceCode": "ODPRC-HB-4",
            "ContactName": "Sudhir",
            "GPS_Lat_Long": "15.396863, 74.012382",
            "DeviceName": "Sudhirs Device"
        }
    ];

    class Devices extends Component {

    constructor(props) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        });
        this.state = {
            dataSource: ds.cloneWithRows(devices)
        }
    }
    componentDidMount() {
        this.getDeviceList();
    }

    getDeviceList() {
        let request = new Request('https://myapiWithQueryString.com');
        request.addHeaders({ 'Content-Type': 'application/json'});  
        RNETWORK.get(request, () => {
        }, (response) => {
            if (response.getError()) {
                alert(response.getError().message);
            } else {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(response.getBodyString())

                });
                alert(response.getBodyString());
            }
        });
    }

Upvotes: 2

Views: 433

Answers (1)

sebastianf182
sebastianf182

Reputation: 9978

Try this:

dataSource: this.state.dataSource.cloneWithRows(JSON.parse(response.getB‌​odyString()))

Note: I am assuming getBodyString actually returns something because I don't recall that method existing in the response interface.

Upvotes: 1

Related Questions