Fetch virtual payment address of users in my react native app - react-native

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);
});
};

Related

Await is only allowed within async functions error react native

I am new to react native and trying to save user obejct in application storage using await AsyncStorage.setItem('user', res[1].data); However I am getting error as
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const {navigate} = this.props.navigation;
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
await AsyncStorage.setItem('user', res[1].data);
navigate('Home');
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};
I have made the handleLogin async but it doesn't solve the error. What is the correct way to store user obejct?
It is recommended that you use react-native-easy-app , through which you can access any data in AsyncStorage synchronously.
Sample_Hooks
StorageController
navigateToHome = async (user) => {
const { navigate } = this.props.navigation;
await AsyncStorage.setItem('user', user);
navigate('Home');
}
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
navigateToHome(res[1].data);
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};

React Native - fetch to setState returns the old value

I'm trying to update a row in database with API request Post when click in button (cancel or finish).
The value is update correctly in database but when i click button onPress={() => { settersApi('Finish'); gettersApi(); }} in gettersApi() console.log(estado) return the old value from hook "estado".
export default Home = ({navigation}) => {
const [estado, setEstado] = useState([]);
const gettersApi = async () => {
try {
let response = await fetch(
'http://api/getValues', {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
}
);
let json = await response.json();
setEstado(json);
console.log(estado);
} catch (error) {
console.error(error);
}
};
useEffect(() => {
gettersApi();
}, []);
const settersApi = async (param) => {
try {
let response = await fetch(
'http://api/setValues', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
body: JSON.stringify({
id: estado.id,
estado: param,
})
}
);
let json = await response.json();
} catch (error) {
console.error(error);
}
};
const CButtons = () => {
return (
<View>
<View>
<Button
color='#ffc107'
title="CANCEL"
onPress={() => {
settersApi('Cancel');
gettersApi();
}}
/>
</View>
<View>
<Button
color='#28a745'
title="FINISH"
onPress={() => {
settersApi('Finish');
gettersApi();
}}
/>
</View>
</View>
);
};
return (
<View style={styles.body}>
<CButtons></CButtons>
</View>
);
};
The function from useState that you called setEtado is a async function. You wont see any changes right away after you change it.
Try to watch the variable state and see when it's updated by using useEffect
useEffect(() => {
console.log(estado);
}, [estado]);

How to pass link parameter from react native fetch method to express js server

I'm trying to pass the link parameter to express js server, so how can i pass through fetch method in react native ?
here is my lines of code to fetch the particular
searchByID = () => {
this.setState({ ActivityIndicator_Loading: true }, () => {
const {ticket} = this.state.ticketid;
fetch('http://192.168.0.108:3000/users/${ticket}',
{
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((res) => {
if (res.success === true) {
alert(res.message);
this.setState({ dataSource: res.message })
AsyncStorage.setItem('userinfo', res);
this.setState({ ActivityIndicator_Loading: false });
}
else {
alert(res.message);
}
this.setState({ ActivityIndicator_Loading: false })
}).done();
})
}
Use the body field.
searchByID = () => {
this.setState({ ActivityIndicator_Loading: true }, () => {
const { ticket } = this.state.ticketid;
fetch('http://192.168.0.108:3000/users/${ticket}',
{
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ a: 1, b: 2 })
})
.then((response) => response.json())
.then((res) => {
if (res.success === true) {
alert(res.message);
this.setState({ dataSource: res.message })
AsyncStorage.setItem('userinfo', res);
this.setState({ ActivityIndicator_Loading: false });
}
else {
alert(res.message);
}
this.setState({ ActivityIndicator_Loading: false })
}).done();
})
}

How to get id from json react-native-material-dropdown

I have used react-native-material-dropdown in my react native project. I am getting a data from API.
I am sorry, my English is bad.
fetch('xxxx.json', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => response.json())
.then((responseJson) => {
var count = Object.keys(responseJson.cities).length;
for(var i=0;i<count;i++){
//console.warn(responseJson.cities[i].name) // I need to add
//these names to dropdown
this.state.drop_down_data.push({ value: responseJson.cities[i].name,id:responseJson.cities[i].id });
}
//this.setState({ drop_down_data });
})
.catch((error) => {
console.error(error);
});
and Dropdown code
<Dropdown
label='City'
data={this.state.drop_down_data}
onChangeText={this.onCityChange.bind(this)}
/>
and Change method issue is here
onCityChange(val,ind,data){ fetch('xxxx/'+ cityid +'/towns.json', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => response.json())
.then((responseJson) => {
this.setState({drop_down_data2: []});
var count = Object.keys(responseJson.towns).length;
for(var i=0;i<count;i++){
//console.warn(responseJson.towns[i].name) // I need to add
//these names to dropdown
//
this.state.drop_down_data2.push({ value: responseJson.towns[i].name,id:responseJson.towns[i].id });
}
//this.setState({ drop_down_data });
})
.catch((error) => {
console.error(error);
});
}
in here i want to city id.value is coming but id not coming or i dont know get to id.
if i can get id, i can a post request for town.
how i can do this?
and some json data
{
"id": 1,
"name": "Adana",
"alpha_2_code": "TR-01"
},
{
"id": 2,
"name": "Adıyaman",
"alpha_2_code": "TR-02"
},
onChangeText Method have 3 parameters (value, index, data)
data = Complete Array
index = Current Item index selected
You can get id by this code
onChangeText = (value, index, data) => {
const cityId = data[index].id;
console.log("cityId", cityId);
};
Complete Sample Code
import React, { Component } from "react";
import { Dropdown } from "react-native-material-dropdown";
const data = [
{
value: "City1",
id: 1
},
{
value: "City2",
id: 2
},
{
value: "City3",
id: 3
}
];
export default class Example extends Component {
onChangeText = (value, index, data) => {
const cityId = data[index].id;
console.log("cityId", cityId);
};
render() {
return (
<Dropdown
label="Favorite Fruit"
data={data}
style={{ marginTop: 50 }}
onChangeText={this.onChangeText}
/>
);
}
}

Set State Inside Async Function in React Native(Expo)

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
})
})