YoungDreamer YoungDreamer - 1 month ago 12
React JSX Question

"Requested keys of a value that is not an object" JSON and React Native

I'm having an issue with React Native that I cannot solve, most likely because I'm pretty new to React and JavaScript so I might not have all the "keys". haha

First, this is the structure of my JSON:

{ "Spot[]": [
{"id":1,"name": "Relais Villenus"},
{"id":2, "name": "Random"}
]}


I did not get to work on a lot of JSON so far but they were never like this and it lost me !

My class requesting the data:

class ListScreen extends Component{
static navigationOptions = {
tabBarLabel: 'Liste',
};

constructor(props) {
super(props);
this.state = {
isLoading: true
}
}

componentDidMount() {
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.Spot),
});
})
.catch((error) => {
console.error(error);
});
}

render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}

return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.name}</Text>}
/>
</View>
);
}
}


I tried different things based on what I've read here or on GitHub like

dataSource: ds.cloneWithRows(responseJson.Spot[]),


or like this:

dataSource: ds.cloneWithRows(responseJson),


and in the view:

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


or

renderRow={(rowData) => <Text>{rowData.Spot[name]}</Text>}


My code works with this JSON: https://facebook.github.io/react-native/movies.json

This is why I assume the error is because I don't know how to properly fetch the data.

Thanks !

Answer Source

You are accessing property in the wrong way. Change you dataSource to

this.setState({
    isLoading: false,
    dataSource: ds.cloneWithRows(responseJson['Spot[]']),
});

You need to access your property using bracket notation.

Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.