Hello people on StackoverFlow,
I'm developing a backend (Laravel) and a frontend (React-Native). The problem is on the frontend, where I'm trying to assign the JSON response to the state. But for some reason I can't set the "this.state.data" to be an array as it always turns out to be a string and instead of an object I get one character at a time.
I want to set the data to be an array of all the routes from the API response.
React-Native code: (OBS: URL REMOVED DUE TO SERVER IS IN DEVELOP MODE)
async getData() {
var token = await AsyncStorage.getItem("token");
this.setState({ "token": token });
fetch('myurl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: this.state.token
})
}).then((response) => {
if (response != null) {
//console.log(response.json());
console.log(response);
this.setState({
//data: response._bodyInit,
data: JSON.stringify(response._bodyInit),
loading: false
});
}
return this.state.data;
})
.catch((error) => {
console.error(error);
});
}
The URL response structure looks like this:
{
routes: [
{
id: '15',
uuid: '26-10-2018',
start_address: 'Krogshøj Alle 3',
end_address: 'Lindevangs Alle 16',
arrival: '27-10-2018 10:00',
},
...
]
}
If I hardcode the data like this, it works.
this.setState({
data:
[
{
id: '15',
uuid: '26-10-2018',
start_address: 'Krogshøj Alle 3',
end_address: 'Lindevangs Alle 16',
arrival: '27-10-2018 10:00',
},
]
});
This is where I use the data:
return (
<View style={styles.container}>
<Toolbar
isHidden={phase !== 'phase-0'}
onBackPress={this.onBackPressed}
/>
<FlatList
key={item => item.id}
data={this.state.data}
dataExtra={{ phase, opacityOfSelectedItem }}
keyExtractor={item => item.id}
renderItem={this.renderItem}
/>
</View>
);