I dont know why but my Rating stars are not updated even though I have called the method. This is my sample code:
import { Rating } from 'react-native-elements-master';
componentDidMount() {
return this.mediavoti()
}
My costructor:
constructor(props) {
super(props);
this.state = {
Mediaevento: '2'
}
}
and this is my method:
mediavoti() {
return fetch('url',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Idevento: this.props.navigation.state.params.TiPasso_Idevento,
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
Mediaevento: responseJson[0].Media
}, function () {
});
}).catch((error) => {
console.error(error);
});
}
This is my Rating render component:
<Rating
type="star"
fractions={1}
startingValue={parseFloat(this.state.Mediaevento)}
imageSize={40}
onFinishRating={this.voto}
showRating
style={{ paddingVertical: 10 }} />
I dont know why but it always sees that the state.mediaevento value is 2. But if I use console.log in mediavoti() method I can see that the state is changed.
Can you try this.
componentWillMount() {
return this.mediavoti()
}
Instead of componentDidMount()
Related
This is my code It is supposed to work but somehow it doesn't. I've also tried to use this JSON https://reactnative.dev/movies.json but I also get the same result
export default class App extends Component {
constructor() {
super();
this.state = {
data: []
}
}
componentDidmount() {
fetch('http://192.168.1.4:8080/api', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(result => {
data = result});
}
render() {
return (
<View>
<Text
style = {{fontSize: 18}}>
Display API JSON DATA
</Text>
<FlatList
data = { this.state.data }
renderItem= { ({item}) =>
<View>
<Text>{item.title}</Text>
<Text>{ this.state.data }</Text>
</View>
}
/>
</View>
)
}
}
This is my JSON file
[{"price":3,"_id":"5f32d2f3f995eb0013ff4be7","title":"new book","__v":0},]
the result is the following
use this.setState() set your component states. learn more
componentDidmount() {
fetch('http://192.168.1.4:8080/api', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(result => {
this.setState({data: result})
});
}
Have you checked doing console.log inside render before flatlist ? What does this.state.data contain
I want to get the returned value "responseData" assigned to the data variable
fetch('http://localhost:8080/users/update, {
method: 'PUT',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
name:this.state.name,
Level:this.state.activity,
height:this.state.height,
weight:this.state.weight
})})
.then((response) => {
return response.json()
})
.then((responseData) => {
console.log(responseData)
this.setState({
data:responseData
})
}
);
I does return true I just want to get it assigned to the variable I already tried to use
this.setState({
data:responseData
})
But it didn't work
fetch('http://localhost:8080/users/update, {
method: 'PUT',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
name:this.state.name,
Level:this.state.activity,
height:this.state.height,
weight:this.state.weight
})})
.then((response) => {
return response.json()
})
.then((responseData) => {
console.log(responseData)
this.setState({
data:JSON.parse(responseData)
})
}
);
#Asad Thank you I figured it out it was my mistake though I tried to assign a json value to a string variable this is the correct code
this.setState({
data:JSON.parse(responseData)
})
search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
How can I use my search function to update my list whenever I enter something in my search box?
This is what I'm trying in my TextInput (SearchBox).
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor= {colors.whiteColor}
onChangeText={
name => {
this.setState({name});
this.search();
}
}
/>
Firstly responseJson is an actual json object, you don't need to stringify it and then parse it.
You could store the responseJson in the state
search = () => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": this.state.name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
Just make sure you set the initial state in your constructor of your component
constructor(props) {
super(props);
this.state = { data: [] }
}
Then you should be able to access your data by using this.state.data
Updated Answer to Updated Question
The problem is that you are not realising that setState is asynchronous. That is takes time for the state to update. That means that you are setting state and then hoping that the state will have updated by the time the next function is called. Unfortunately, calling setState in your TextInput is not having the desired effect.
I would update your search function to the following
search = (name) => {
fetch(strings.baseUri+"search_by_name", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"name": name,
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson, name: name});
})
.catch((error) => {
this.setState({name: name});
console.error(error);
});
}
Then in yourTextInput update your function call to
<TextInput style={styles.searchInput}
placeholder="Search"
placeholderTextColor={colors.whiteColor}
onChangeText={ name => {
if (name.length > 0) {
this.search(name);
} else {
this.setState({data: [], name: ''});
}
}
}
/>
This will reduce the number of times setState is called.
uhm...
i'm not sure what 'body' part is for..
i mean the part
body: JSON.stringify({"name": this.state.name})
maybe is better like
body:[{'name':bla}] ?
anyway, try with this (and write 'Accept' header as a string):
(add the body part if is so important to you)
const fetchConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
fetch(strings.baseUri+"search_by_name",fetchConfig)
.then((response) => {
//use *return* statement to return a json object to THEN part
return JSON.parse(response)
})
.then((responseJson) => {
let jsonObj = responseJson;//responseJson is *already* a JSON object.
//you cannot alert a JSON data, it's will show as [object]
//you can do console.log() or
//console.warn() <--- this will showed on device in yellowbox, but i'm not sure about a json data.
})
I want to fetch multiple API requests in componentDidMount() function. I have a picker which take items from API call. I have another API which returns a picker value. Now i want to set selected the value received in latter API in the picker. I am trying to fetch both API in componentDidMount function
Here is my code. Please suggest where i am missing.
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';
export default class FirstProject extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true,
PickerValueHolder : ''
}
}
componentDidMount() {
const base64 = require('base-64');
// my API which fetches picker items
return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
// another api which fetches a particular fruit_id from database which i ave to set selected in picker.
fetch('http://my_api_url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"fruit_id":"123"
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
PickerValueHolder: responseJson,
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<Picker
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{ this.state.dataSource.map((item, key)=>(
<Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
)}
</Picker>
<Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10
}
});
As you said in comment, your second API response:
[{"fruit_id": "123","fruit_name":"Strwaberry"}]
So it might work with minor changes:
.then((responseJson) => {
this.setState({
isLoading: false,
PickerValueHolder: responseJson[0].fruit_name,
}, function() {
// In this block you can do something with new state.
});
})
i want to display my JSON in a Listview. the problem is i dont know how to use code for display my JSON data
enter image description here
this is my JSON respone. i want to show nama and harga_jual
import React, { Component } from 'react';
import {
StyleSheet,
Text,
AsyncStorage,
Alert,
ListView,
View
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { Header, Container, Content, Icon, Left, Body, Right, Button, Title, Card, CardItem, Thumbnail} from 'native-base';
export default class Product extends Component {
constructor(props) {
super(props);
var dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state={
iduser: '',
idgrup_outlet: '',
url:'',
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
}
}
async componentWillMount() {
const value = await AsyncStorage.getItem('iduser').then((value) => {
this.setState({
'iduser': value
});
console.log("ID User is : " + this.state.iduser);
})
const value1 = await AsyncStorage.getItem('idgrup_outlet').then((value) => {
this.setState({
'idgrup_outlet': value
});
console.log("ID Group Outlet is : " +(this.state.idgrup_outlet));
})
const value2 = await AsyncStorage.getItem('url').then((value) => {
this.setState({
'url': value
});
console.log("URL is : " + this.state.url);
})
console.log("ID User is : " + this.state.iduser);
let response = await fetch('http://'+this.state.url+'/web_services/list_produk/new.json', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
erzap: {
iduser: this.state.iduser,
idgrup_outlet: this.state.idgrup_outlet,
}
})
});
let responseJson = await response.json();
// console.log(JSON.stringify(responseJson.produks[nama]));
console.log(JSON.stringify(responseJson.produks));
}
render() {
return (
<Container>
<Header style={{backgroundColor: '#03A9F4'}}>
<Left>
<Button transparent>
<Icon name='menu'/>
</Button>
</Left>
</Header>
<Content>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.nama}</Text>}
/>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
carditem: {
paddingLeft: 10,
},
});
this my code
What you can do here is to set the state of your dataSource to responseJson in the componentWillMount method. So it would look something like this:
// ... the rest of the code
let responseJson = await response.json();
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseJson),
});