Method called on render without click react native - reactjs

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

Related

How do I set get the specific array index of JSON response array to TextInput in React Native

I am able to fetch my complete response in react native the code is as follow to fetch the data
import React, { Component } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
}
}
componentDidMount() {
let content = '/LoginPageLoad_Arr';
const url = 'abc.asmx' + content;
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
})
.then((response) => response.json())
.then((responseJson) => {
const result = JSON.parse(responseJson.d)
this.setState({
dataSource: result.Table1
})
}).catch((error) => {
console.error(error);
});
}
_renderItem = ({ item }) => (
<TouchableOpacity>
<View>
<Text>
{item.ID} = {item.VALUE}
</Text>
</View>
</TouchableOpacity>
)
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
// keyExtractor={(item, index) => index}
/>
</View>
)
}
}
My concern is to fetch the ID and VALUE at the index 0. I tried adding the code item.ID[0] it just fetch me the first letter of all the ID. I want complete complete ID at just index 0 to set in TextInput. Please if someone as worked on it help me out.
First, better method is to cut your function in ComponentDidMount, and use async instead of .then() like :
ComponentDidMount(){
this.callApiFunction();
}
async callApiFunction(){
try{
let content = '/LoginPageLoad_Arr';
const url = 'abc.asmx' + content;
const call = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
})
call = call.json();
call = JSON.parse(call.d)
//If you want to browse an array, you can use the map function
call.map((item, index) => {
//And make condition here, for exemple the first element
if(index == 0){
//DO what u want
console.log(item)
this.setState({
dataSource: item
})
}
})
}).catch((error) => {
console.error(error);
});
}
catch(e){
console.log(e)
}
}
Hope it will help you

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

on press post the variables to database (react native)

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

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

Resources