Reputation: 627
React-Native fetch JSON by Tutorial Facebook return Error
Error with null is not an object (evaluating 'this.state.datasource')
How Can i do with my code
class ModuleRecView extends Component {
componentWillMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
/>
</View>
);
}
}
export default ModuleRecView;
Upvotes: 0
Views: 632
Reputation: 11
I think the problem is with this link https://facebook.github.io/react-native/movies.json it returns 404 page not found. you can try using another json link or find the data you need here https://github.com/facebook/react-native/blob/master/website/src/react-native/movies.json
Upvotes: 1
Reputation: 9674
I usually do it like this:
import React, { Component } from 'react'
import { ListView, View, Text } from 'react-native'
class ModuleRecView extends Component {
state = {
datasource: new ListView.DataSource({rowHasChanged: (r1, r2) => r2 !== r2}),
isLoading: true
}
componentWillMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: this.state.datasource.cloneWithRows(responseJson.movies),
}, () => {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.datasource}
renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
/>
</View>
);
}
}
export default ModuleRecView;
Please note that RN now has a new Component called <FlatList/> which is the same as the <ListView/>
component but by far better.
Upvotes: 0
Reputation: 8936
Right above componentWillMount
do:
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([]),
};
}
Upvotes: 0