Every time my app runs the keyborad seems to run slower than expected, i have a recursive call that updates an alert every 500 milli-seconds but is this why the keyboard is running slow when typing or is this a seperate issue. I dont have code to show you as everything else in the app runs fast apart from the keyboard. I have js dev mode disabled aswel.
Any clues?
<AutoGrowingTextInput underlineColorAndroid="transparent" style={{flex:1}}
maxHeight={200}
minHeight={45}
placeholder="Message..."
style={{backgroundColor:'#ffffff',}}
onChangeText={(message) => this.setState({message})}
value={this.state.message}
/>
getLatestMessagesRecurse = () =>{
return fetch('http://example.com/example.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
example: example,
example: example
}),
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson != false){
this.setState({_messageAlert: true});
}else{
this.setState({_messageAlert: false});
}
})
.catch((error) => {
alert(error);
});
}
componentDidMount() {
this._interval = setInterval(() => {
this.recurse();
}, 500);
}
recurse = () => {
this.getLatestMessagesRecurse();
}
componentWillUnmount() {
clearInterval(this._interval);
}
Related
I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
I have integrated react-native-upi-payment in my app. The RNUpiPayment Component calls initializePayment method here which gives only vpa for a default user. How can I give vpa address for many users in my database by fecth api or any other methods? Any methods or suggestions please.
My code is here
<TouchableOpacity
style={styles.payBtn}
activeOpacity={0.5}
onPress={() => {
RNUpiPayment.initializePayment(
{
vpa: '8856452125#ybl', // or can be john#ybl or mobileNo#upi
payeeName: 'Stanlee',
amount: '20',
transactionRef: 'aasf-332-aoei-fn',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
}}>
<Text style={styles.payBtnTxt}>PAY</Text>
</TouchableOpacity>
Finally got it!
DriverPaymentFunction = () => {
const {DriverUPI} = this.state;
const {DriverName} = this.state;
fetch('http://ip/appname/payment.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
upi_id: DriverUPI,
driver: DriverName,
}),
})
.then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if (responseJson === 'Data Matched') {
RNUpiPayment.initializePayment( //Payment API
{
vpa: DriverUPI, // or can be john#ybl or mobileNo#upi
payeeName: DriverName,
amount: '0',
transactionRef: 'AppName Ride Transaction',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
} else {
Alert.alert(responseJson);
}
})
.catch((error) => {
console.error(error);
});
};
I don't know if it is a bug or something wrong with my code. But the first fetch takes to long to respond.
Although this problem is only on the app. When I run it on the web, it works like a charm and load within 2 to 3 seconds. While on the app it takes more than a minute.
fetch(url)
.then((response)=>response.json() )
.then((responseJson)=>{
setDATA(responseJson);
setLoading(false);
})
.catch((err)=>{
console.log(err)
})
I also used Axios but having the same problem
axios.get(url)
.then(res => {
setDATA(res.data);
setLoading(false)
console.log(DATA);
})
If you think this can be a large data problem. the SQL db has only 2 field to fetch from.
And It is same when i try to login user. Same slow fetch and slow response
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password
}),
})
.then(response => response.json())
.then((responseJson) => {
setLoading(false);
// If server response message same as Data Matched
if (responseJson === 'Data Matched') {
// save user to async
// AsyncStorage.setItem('isLoggedIn', true);
//send user to main page
navigation.navigate('flatlist');
} else {
alert(responseJson);
console.log(responseJson)
}
})
.catch((error) => {
setLoading(false);
console.log(error);
});
};
It also seems like a bug as I read this
I use promise.All to wait finish methods before render component.
I used like this :
constructor(props) {
super(props);
this.controllAll();
}
controllAll() {
Promise.all([this.callFetch()])
.then(([fetchResponse]) => {
console.log('finished', fetchResponse);
})
.catch(err => {
console.log('Mistake:', err);
});
}
callFetch() {
fetch('url', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
})
.then((response) => response.text())
.then(leaders => {
this.PutImagesToObject(leaders );
});
}
I want to wait to finish callfetch() method finish before render Component. But when I run, firstly in debug mode I see 'finished'.
Doesnt have to wait to finish CallFetch() method to show me 'finished'
Try to add return statement
callFetch() {
return fetch('url', {
...
I am using Expo of React Native which i need to save the API Fetch response to state.
My code is like this:
onPress={async () => {
if (this.camera) {
const options = { quality:0, base64: true};
let photo = await this.camera.takePictureAsync(options);
setTimeout(()=>{
fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
base64: photo['base64'],
}),
}).then((responseJson) => {
this.setState({
response:responseJson
})
})
.catch((error) => {
console.error(error);
});
this.setState({captured:true})
}, 3000)
}
}}
I want to store the response in the state variable named 'response'. But When I want to display the response saved in state, it will render null.
if(this.state.captured){
console.log(this.state.response)
return(
<View style={styles.container}>
<SectionList
sections={[
{title: 'response1', data: [this.state.response]}
]}
renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}else{
...
Here, console.log(this.state.response) shows {} i.e null value. Is it the problem of async function which is not displaying the value saved in state.
No definitely not, as long as your API does return a result, but you should do this.
onPress={async () => {
if (this.camera) {
const options = { quality:0, base64: true};
let photo = await this.camera.takePictureAsync(options);
setTimeout(()=>{
await fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
base64: photo['base64'],
}),
}).then(function(response) {
return response.json()
}).then((responseJson) => {
this.setState({
response:responseJson
})
})
.catch((error) => {
console.error(error);
});
this.setState({captured:true})
}, 3000)
}
}}
You missed a few lines there.
You need to extract the response firstly so you have to write one then before your setState then promise like below where reponse.json() extract the actual response and pass it to the responseJson. Thanks, hope it will usefull for you.
.then(reponse => response.json())
.then((responseJson) => {
this.setState({
response:responseJson
})
})