on press post the variables to database (react native) - reactjs

i have this
POST api http://myIP/api/confirm
that post the name , text , service_name , office_name , date , time
and i want to use it to post this variables in react native
on press in botton post these variables and give me alert message
how can i do this
here is my react native code
<View>
<Text> {this.props.navigation.state.params.name}- {this.props.navigation.state.params.text} </Text>
<Text> {this.props.navigation.state.params.service_name}</Text>
<Text>{this.props.navigation.state.params.office_name}</Text>
<Text>{this.props.navigation.state.params.date}</Text>
<Text{this.props.navigation.state.params.time} </Text>
<Button rounded
title='next'
onPress={() => {
Alert.alert('The Appointment booked') }} />
</View>

you can do the following
fetch("http://myIP/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
firstParam: "yourValue",
secondParam: "yourOtherValue"
})
})
.then(response => response.json())
.then(responseJson => {
Alert.alert(
"Alert Title",
"My Alert Msg",
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
})
.catch(error => {
console.error(error);
});
but please import the Alert from react-native

Related

Method called on render without click react native

I am having an issue where a method is being called automatically on render in my react native application. Here are the snippets:
static navigationOptions = ({navigation}) => {
return {
headerTitle: 'Network',
headerRight: () => (
<View style={{flexDirection: 'row'}}>
<Button
title='Invite'
color='#ccc'
onPress={() => navigation.navigate('InviteUser')}
/>
<Button
title='Search'
color='#ccc'
onPress={() => navigation.state.params.handleSearch}
/>
</View>
),
};
};
componentDidMount() {
this.state = {
dataSource:[],
};
this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})
}
It's happening specifically for the search button. Invite works fine. I am pretty new to RN still, so can anyone give some help please?
Edit* added getNearbyUser():
getNearbyUsers(user_id, auth_token) {
console.log('Get Users: id:' + user_id);
let formData = new FormData();
formData.append('user_id', user_id);
formData.append('auth_token', auth_token);
fetch("https://{url}", {
method: 'POST',
header: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
//JSON.stringify({'user_id': user_id, 'auth_token': auth_token})//, 'latitude': 33.0296843, 'longitude': -96.7059628})
}).then(response => response.json())
.then((responseJson) => {
// console.log(responseJson.users[0])
this.createSearchList(responseJson.users)
}).catch((error) => {
console.log('Local Network Error: ' + error)
})
}
Change
this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})
To
this.props.navigation.setParams({ handleSearch: () => this.getNearbyUsers(user_id, auth_token)})

i'm Trying to make react paypal button that change the billing amount on props change

i'm Trying to make react paypal button that changes the billing amount on props change.
I call the following component with props price and everytime the price change i would like to rerender the button to update the actual price.
const PaypalForm = props => {
let paypalRef = useRef();
useEffect(() => {
window.paypal
.Buttons({
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [
{
description: "test",
amount: {
currency_code: "USD",
value: props.price
}
}
]
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
console.log(order);
},
onError: err => {
setError(err);
console.error(err);
}
})
.render(paypalRef.current);
}, [props.price]);
return (
<Row className="justify-content-center">
{error && <div>Uh oh, an error occurred! {error.message}</div>}
<div ref={paypalRef} />
</Row>
);
};
Everything is working except that a new button is created and added in the bottom of old one at each props change. I would like my new button to replace the old one.
You can pass the amount to the forceRerender property of the button and the button will rerender each whenever the amount is updated.
You should really just use react-paypal-button-v2
It updates with props, works as a stateless function and works with SSR such as next.js.
It even allows bypassing actions.order.create() so that you can call your own API's.
import { PayPalButton } from "react-paypal-button-v2";
const PaypalButton = ({total, cart}) => {
return (
<PayPalButton
createOrder={(data, actions) => {
return fetch('/api/paypal/create-transaction', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
total: total,
cart: cart,
})
})
.then((response) => {return response.json()})
.then((data) => {return data.orderID})
.catch(error => console.log(error))
}}
onApprove={(data) => {
// Capture the funds from the transaction
return fetch('/api/paypal/capture-transaction', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ orderID: data.orderID })
})
.then((res) => { return res.json() })
.then((details) => {
if(details === 200){
console.log('success');
} else {
console.log('failure');
}
})
.catch(error => {
console.log(error)
})
}}
options={{
clientId: process.env.PAYPAL_CLIENT_ID
}}
/>
);
}
export default PaypalButton;

React-Native: Display JSON Data

function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
// body: `root=auto&path=${Math.random()}`
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
})
.catch(err => {
console.error('Error: ', err);
});
}
export default class App extends Component {
connectFitbit = () => {
OAuth(client_id, getData);
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to Fitbit Integration</Text>
<Button title="connect fitbit" onPress={() => this.connectFitbit()} />
</View>
);
}
}
I'm trying to get fit bit steps JSON data in react native app ,
right now I am getting the output in console ,now i want to parse the step data in my app please help me out
If you want to display your data in to flatlist...
First you need to make array for saving your response data..
constructor(props) {
super(props);
this.state = {
...
result: [],
...
};
}
function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
// if your response have anu json array
this.setState({
result:res.data,
});
})
.catch(err => {
console.error('Error: ', err);
});
}
After, in flatlist simply set this array,
<FlatList
data={this.state.result}
renderItem={item => your render view}
keyExtractor={(item, index) => your key item}/>

Access object in JSON array with this.state in React Native

I am having trouble displaying an object from an array. I want to display id from here:
[
{
"id":"1",
"imagename":"dog"
},
{
"id":"2",
"imagename":"cat"
},
{
"id":"3",
"imagename":"mouse"
},
{
"id":"4",
"imagename":"deer"
},
{
"id":"5",
"imagename":"shark"
},
{
"id":"6",
"imagename":"ant"
}
]
Here is my attempt:
fetch(`http://www.example.com/React/data.php` , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
id: responseJson[0].id, <-- Attempt to try to get the id from responsejson.
},function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
With this I got undefined is not a function. I am not getting what I am doing wrong or how to access this object.
<FlatList
data={ this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <View>
<Card>
<View>
<Text style={{marginTop: 30}}> {this.state.responseJson.id}</Text>
</View>
</Card>
</View>
}
keyExtractor={(item, index) => index.toString()}
/>
Try the async/await method, you are getting an error because the data is not load and the render function is trying to load the data.
async componentDidMount() {
await fetch(`http://www.example.com/React/data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => response.json()).then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
id: responseJson[0].id
});
}).catch((error) => {
console.error(error);
});
}
Or another approach is to add a loading preloader or spinner like this.
First import the package.
import { ActivityIndicator } from 'react-native';
Second change the render method
render() {
if (isLoading) {
return ( <
View style = {
[styles.container, styles.horizontal]
} >
<
ActivityIndicator size = "large"
color = "#0000ff" / >
<
/View>
);
}
return (
// Your render stuffs
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 10
}
})
If any issue please let me know

Connect two modal picker in react native

I use react native modal picker to drop down the data link here
I used two modal picker, that depend on each other. first one is select service. second one is select city. I want to display cities that have particular services. code is here
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Alert,
TouchableHighlight,
Image,
TextInput,
} from 'react-native';
var fullservice=[];
var citylist=[];
import ModalPicker from 'react-native-modal-picker'
class jsonSugei extends Component {
constructor() {
super();
this.state = {
textInputValue: '',
dropdownservices:[],
city:'',
dropdowncities:[],
service:'',
}
}
componentDidMount() {
this.fetchData1();
this.fetchData2();
}
fetchData1(){
fetch("URL",
{method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( {"cacheRequest":["ALL_COMPANY","ALL_SERVICE","HOT_COMPANY","BANNER","PARTNER","CITY","CALANDAR","COMMENTS "]}),
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
dropdownservices: responseData.services,
});
})
.catch((error) => { console.warn(error); })
.done();
}
fetchData2(){
this.state = {
service:'',
}
fetch("URL",
{method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( {
"companyId":"",
"service":this.state.service,
"key":""
}),
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
dropdowncities: responseData.cities,
});
})
.catch((error) => { console.warn(error); })
.done();
}
render() {
citylist= this.state.dropdowncities.map(function(item) {
return {
key:item.id,
label: item.name,
};
});
fullservice =this.state.dropdownservices.map(function(item) {
return {
key:item.id,
label: item.name,
};
});
return (
<View style={{flex:1, justifyContent:'space-around', padding:50, backgroundColor: '#ffffff'}}>
<ModalPicker1
data={fullservice}
initValue="Select Services!"
onChange={(option)=>{this.setState({service:option.label})}}
/>
<ModalPicker
style={{marginTop:10}}
data={citylist}
initValue="City"
onChange={(option)=>{ this.setState({city:option.label})}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
button: {
borderRadius: 4,
padding: 10,
marginLeft: 10,
marginRight: 10,
backgroundColor: "#B8C",
},
});
AppRegistry.registerComponent('jsonSugei', () => jsonSugei);
but not change cities according to the services??? I need help............
The onChange event handler for services ModalPicker should set the state for the cities ModalPicker. Also, the initial fetch for the cities ModalPicker should only fetch cities corresponding to the default service.
Add another function to first modal picker, and set the data entity as a get state variable,
<ModalPicker1 data={fullservice} initValue="Select Services!" onChange={(option)=>{this.setState({service:option.label}),this.secondFunction()}} />
Then set the state.cities variable in the second function and use it as the data entity in second modal picker,
secondFunction(){
this.setState({cities:array});
}
<ModalPicker2 data={this.state.cities} initValue="City" onChange={(option)=>{this.setState({city:option.label})}} />

Resources