Reputation: 469
I'm trying to display the axios response data in the react native front end.I don't have a clear understand how to do it.
I tried to store the response data into an array and display it as a flat list.But still not getting the out put
import React, {Component} from 'react';
import axios from 'axios';
import {StyleSheet, Text, View, TextInput, Button, FlatList} from 'react-native';
const serverURL ='http://192.168.8.100:5000';
const http = axios.create({
baseURL:serverURL,
});
export default class App extends Component {
constructor(props){
super(props);
this.state = {
treeType:'',
midgirth:'',
length:'',
rslt:[],
};
}
onCalculate(){
const{treeType,midgirth,length,rslt} = this.state;
http.post('/calculations',{
treeType:treeType,
midGirth:midgirth,
length:length
})
.then(function(response){
rslt.push(response.data);
alert("Response :",response.data);
console.log(response.data);
console.log(rslt);
})
.catch(function(error){
alert("Error",error);
});
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.textinput}
placeholder="Tree Type"
onChangeText={(val)=>this.setState({treeType:val})}
/>
<TextInput style={styles.textinput}
placeholder="Mid-Girth"
underlineColorAndroid={'transparent'}
onChangeText={midgirth=> this.setState({midgirth})}
/>
<TextInput style={styles.textinput}
placeholder="Length"
underlineColorAndroid={'transparent'}
onChangeText={length=> this.setState({length})}
/>
<Button title='Calculate' onPress={()=>this.onCalculate()}/>
<FlatList
data={this.state.rslt}
renderItem={({item}) => <Text>{item}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
textinput: {
backgroundColor:'rgba(255,255,255,0.7)',
borderRadius:20,
paddingHorizontal:16,
color:'#000000',
fontSize:25,
marginVertical:10,
borderWidth:3,
borderColor: '#005662',
margin:10,
},
});
When the user clicked the button I need to send the post request to backend and display the response data in the front end
Upvotes: 1
Views: 351
Reputation: 2220
This is because you are mutating the state rather than calling setState which tells react to re-render your component.
You need to do something like this:
http.post('/calculations', {
treeType: treeType,
midGirth: midgirth,
length: length
})
.then(function (response) {
rslt.push(response.data);
this.setState({rslt}); // or this.forceUpdate();
alert("Response :", response.data);
console.log(response.data);
console.log(rslt);
}.bind(this))
.catch(function (error) {
alert("Error", error);
});
Upvotes: 1