I am trying to add selected item data in an SQLite cart table but it's not getting filled :
SelectItem is selecting the item and in console it's showing and all fields are not null or undefined. All fields have data but still it's not working:
const SelectItem = id => {
console.log('Inside SelectItem');
itemData.filter((val, i) => {
if (val.itemid == id) {
const DATAs = {
itemid: val.itemid,
itemname: val.itemname,
qty: qty,
discount: disc,
price: 100,
amount: 100 * qty,
netamount: 100 * qty - disc,
};
console.log(
'{' +
DATAs.itemid +
', ' +
DATAs.itemname +
', ' +
DATAs.qty +
', ' +
DATAs.price +
', ' +
DATAs.discount +
', ' +
DATAs.netamount +
'}',
);
try {
console.log('Inside try');
db.transaction(function (tx) {
tx.executeSql(
'INSERT INTO tmpCart (orderdate, partyid, partyname, partyaddress, itemid, itemname, qty, price, amount, discount, netamount) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
[
new Date().toLocaleDateString(),
route.params.custObj.partyid,
route.params.custObj.partyname,
route.params.custObj.partyname,
DATAs.itemid,
DATAs.itemname,
DATAs.qty,
DATAs.price,
DATAs.amount,
DATAs.discount,
DATAs.netamount,
],
(tx, results) => {
console.log('Results', results.rowsAffected);
if (results.rowsAffected > 0) {
alert(
'Success',
'You are Registered Successfully',
[
{
text: 'Ok',
onPress: () => navigation.navigate('Menu'),
},
],
{cancelable: false},
);
} else alert('Registration Failed');
},
);
});
} catch (err) {
console.log('ERROR tmpCart: ' + err);
}
}
});
};
I checked all console.logs and the data is OK but is not filling the table and when I print data in cart page the array is empty :
[]
cart page:
const Cart = () => {
const [cartData, setCartData] = useState([]);
const [searchFilter, setSearchFilter] = useState('');
useEffect(() => {
setCartData(getCartData(db));
}, []);
useEffect(() => {
console.log(cartData);
}, [searchFilter]);
return (
<View>
<Search ph={'Search cart'} setSearchFilter={setSearchFilter} />
<FlatList
extraData={searchFilter}
data={cartData.filter(item => {
if (searchFilter === '') {
return item;
} else if (
item.partyname
.toString()
.toLowerCase()
.includes(searchFilter.toLowerCase())
) {
console.log(item);
return item;
}
})}
renderItem={({item}) => (
<Text style={{color: '#fff'}}>{item.itemname}</Text>
)}
keyExtractor={item => item.itemid}
/>
</View>
);
};
Related
I have a following function in Api.js
const _getCategories = async () => {
var categories = [];
let token = await getJwt();
var config = {
method: 'get',
url: 'myurl',
headers: {
'Authorization': 'Bearer' + ' ' + token
},
data : ''
};
axios(config)
.then(function (response) {
if(response.status == 200)
{
let res = response.data;
// Create a variable having name in the list.
categories = res.data.apps.map(function(item) {
return {
title: item.name,
color: AppStyles.colorSet.analyticsColor,
lightColor: AppStyles.colorSet.analyticsLightColor,
icon: AppStyles.iconSet.analytics
};
});
// console.log('Returning Categories');
console.log(categories);
return categories;
//console.log(data1)
// Handle and fetch the list of apps
}
else
{
// API didn't go through, generate the error functions
}
})
.catch(function (error) {
console.log(error);
});
};
and I am loading it in homscreen.js
class DashboardScreen extends React.Component {
constructor(props) {
super(props);
const { navigation } = props;
navigation.setOptions({
title: 'Dashboard',
headerLeft: () => (
<TouchableOpacity
onPress={() => {
navigation.openDrawer();
}}
>
<Icon
style={AppStyles.styleSet.menuButton}
name="ios-menu"
size={AppStyles.iconSizeSet.normal}
color={AppStyles.colorSet.mainThemeForegroundColor}
/>
</TouchableOpacity>
),
});
this.state = {
categories: [],
};
}
componentDidMount() {
if (!this.state.data) {
Api.getCategories().then(data => console.log("The data is "+data))
.catch(err => { /*...handle the error...*/});
}
}
onPressCategory = item => {
// Handle onpress for the items
};
render() {
//console.log(this.state.categories);
categoryButtonsRow1 = this.state.categories.map((item, index) => {
if (index < 3) {
return (
<CategoryButton
onPress={() => this.onPressCategory(item)}
color={item.color}
lightColor={item.lightColor}
icon={item.icon}
title={item.title}
/>
);
}
});
return (
<ScrollView style={styles.container}>
<View style={styles.row}>{categoryButtonsRow1}</View>
</ScrollView>
);
}
}
But I am getting category as undefined while printing in render().
I even tried to create an async function in the homescreen.js and call the api with await and set the state after the same but still it is coming as undefined.
Any guesses to what I am doing wrong here. Can anyone help with the same. My best guess is that I am not handling the api request properly.
EDIT
I tried Use Async/Await with Axios in React.js but it is still printing undefined to the same.
The reason for getting undefined is the _getCategories is that its not returning anything and you are chaining using .then to get data so the caller has no way to get this data as a callback is not passed.
You can change the to await like this
const _getCategories = async () => {
var categories = [];
let token = await getJwt();
var config = {
method: 'get',
url: 'myurl',
headers: {
Authorization: 'Bearer' + ' ' + token,
},
data: '',
};
const response = await axios(config);
if (response.status == 200) {
let res = response.data;
// Create a variable having name in the list.
categories = res.data.apps.map(function (item) {
return {
title: item.name,
color: AppStyles.colorSet.analyticsColor,
lightColor: AppStyles.colorSet.analyticsLightColor,
icon: AppStyles.iconSet.analytics,
};
});
// console.log('Returning Categories');
console.log(categories);
return categories;
//console.log(data1)
// Handle and fetch the list of apps
} else {
// API didn't go through, generate the error functions
return null;
}
};
And you can set the state in componentDidMount (should be async)
this.setState({categories:await api._getCategories()});
The entire payment is done properly. Here is the code:
'''
const that = this;
function makePayment(){
var options = {
description: 'Bank payment',
currency: 'INR',
key: 'xxx',
amount: that.state.amount_razorpay,
name: 'xyz',
order_id: that.state.id,
prefill: {
email: 'xxx#gmail.con',
contact: '123',
name: 'XYZ'
},
theme: {color: '#53a20e'}
}
RazorpayCheckout.open(options,razr_successCallback,razr_errorCallback)
}
function razr_successCallback(data){
console.log('success',data.razorpay_payment_id);
that.setState({razr_Status:"SUCCESS"});
that.setState({razr_txnId:data.razorpay_payment_id});
// that.props.navigation.navigate('Secured');
}
function razr_errorCallback(data){
console.log('failure',data);
}
'''
The console at razr_successCallback() is giving proper result {"razorpay_payment_id": "pay_Eby2FPTakKuSrz"} but the app is exiting immediately without navigation back to the payment page. I even tried that.props.navigation.navigate('Secured') but still the payment page is not redirected. What is the problem?
Edit 1 :
'''
RazorpayCheckout.open(options)
.then(async data =>
await razr_successCallback(data);
})
.catch(error => {
console.log("payment error", error);
});
async function razr_successCallback(data){
console.log(data);
that.props.navigation.goBack();
}
'''
Still facing same problem
This returns a promise, try it this way :
RazorpayCheckout.open(options)
.then(data => {
// handle success
razr_successCallback(data);
})
.catch(error => {
console.log("payment error", error);
});
in My Case :
const razorpayOpenModal = (razorpay_id, currency) => {
let options = {
description: "Credits towards consultation",
image: images.logo,
currency: currency,
order_id: razorpay_id,
key: RAZOPAY_KEY,
amount: totalAmount * 100,
external: {
wallets: ["paytm"]
},
name: "MyApp.jo",
prefill: {
email: userFromCtxt && userFromCtxt.email,
contact: userFromCtxt && userFromCtxt.phone,
name: userFromCtxt
? userFromCtxt.first_name + " " + userFromCtxt.last_name
: ""
},
theme: { color: color.primaryHeaderColor }
};
RazorpayCheckout.open(options)
.then(async data => {
setPaymentId(data.razorpay_payment_id);
await setShowModel(true);
})
.catch(error => {
console.log("payment error", error)
});
};
and then on model :
<MessageModal
button={true}
primaryMessage={primaryText}
secondaryMessage={secondaryText}
visible={modalVisible}
transactionResp={transactionResp}
closeModal={async () => {
setModalVisible(false);
await props.navigation.navigate("Home");
}}
buttonText={"Continue"}
image={transactionResp ? images.success : null}
onPressButton={async () => {
setModalVisible(false);
await props.navigation.navigate("Home");
}}
/>
I tried fetching values from server for multi select picker component from the package https://github.com/toystars/react-native-multiple-select. But i get an error message: TypeError: null is not an object(evaluating this.state.LangKnown).
Please Kindly help.Thank u
My JSON values
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
import React, {Component} from "react";
import { Text, View, StyleSheet, Picker, Alert } from "react-native";
import MultiSelect from "react-native-multiple-select";
export default class App extends React.Component {
state = {
LangPickerValueHolder: [],
LangKnown: []
}
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(response => response.json())
.then(responseJson => {
let langString = responseJson.MFBasic.Languages;
let langArray = langString.split(',');
this.setState({
LangPickerValueHolder: langArray
});
}).catch(error => {
console.error(error);
});
}
render () {
return (
<View style={styles.itemContainer}>
{<MultiSelect
ref={(component) => { this.multiSelect = component; }}
onSelectedItemsChange={(value) =>
this.setState({ LangKnown: value })
}
selectedItems={this.state.LangKnown}
onChangeInput={ (text) => console.log(text)}
displayKey = ''name
submitButtonText="Submit">
{this.state.LangPickerValueHolder.map((item, key) => (
<MultiSelect.Item item = {item} uniqueKey = {key}/>
))}
</MultiSelect>}
</View>
);
}
}
You've made a good attempt at how to set up the MultiSelect however there are a couple of issues that need to be resolved.
If you look at the dependency the data that should be passed to it should be an array of objects. The example gives the object as { id: '92iijs7yta', name: 'Ondo' } We can easily transform your data from an array of strings into an array of objects that match the example.
let LangPickerValueHolder = langArray.map((name, id) => { return { name, id }; });
Using a map we can convert the array.
This would make your componentDidMount look like the following:
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(response => response.json())
.then(responseJson => {
let langString = responseJson.MFBasic.Languages;
let langArray = langString.split(',');
let LangPickerValueHolder = langArray.map((name, id) => { return { name, id }; }); // <- here we had the mapping function
this.setState({ LangPickerValueHolder }); // <- save the new array of objects into the state
console.log(langArray);
}).catch(error => {
console.error(error);
});
}
Setting up the MultiSelect component requires a few more changes.
Firstly there is no MultiSelect.Item so the map that you are using to populate the MultiSelect won't work. Instead you need to use the items prop to set the items. Next you need to tell the MultiSelect component the correct uniqueKey prop (which in our case will be id) and set the displayKey correctly.
Here is what your render could look like.
render () {
return (
<View style={styles.container}>
<MultiSelect
ref={(component) => { this.multiSelect = component; }}
onSelectedItemsChange={(value) =>
this.setState({ LangKnown: value })
}
uniqueKey="id"
items={this.state.LangPickerValueHolder}
selectedItems={this.state.LangKnown}
onChangeInput={ (text) => console.log(text)}
displayKey = 'name'
submitButtonText="Submit" />
</View>
);
}
Here is it put together in a snack: https://snack.expo.io/#andypandy/multiselect-with-data-from-api
Here is the code from the snack:
import React from 'react';
import { View, StyleSheet } from 'react-native';
import MultiSelect from 'react-native-multiple-select';
export default class App extends React.Component {
// declaring state like this is absolutely fine, it doesn't need to be in a constructor
state = {
LangPickerValueHolder: [],
LangKnown: []
}
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(response => response.json())
.then(responseJson => {
let langString = responseJson.MFBasic.Languages;
let langArray = langString.split(',');
let LangPickerValueHolder = langArray.map((name, id) => { return { name, id }; });
this.setState({
LangPickerValueHolder
});
console.log(langArray);
}).catch(error => {
console.error(error);
});
}
render () {
return (
<View style={styles.container}>
<MultiSelect
ref={(component) => { this.multiSelect = component; }}
onSelectedItemsChange={(value) =>
this.setState({ LangKnown: value })
}
uniqueKey="id" // <- set the value for the uniqueKey
items={this.state.LangPickerValueHolder} // <- set the items you wish to show
selectedItems={this.state.LangKnown}
onChangeInput={ (text) => console.log(text)}
displayKey = 'name' . // <- fix typo here
submitButtonText="Submit" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: 'white',
padding: 8
}
});
I am getting data from a google calendar api and store it into a state (which works fine, as console.log shows the data).
But when I add this.state.items to the the flatlist data, it gives me the error:
Tried to get frame for out of range index 0
This is how I get the data:
constructor(props) {
super(props);
this.state = {
items: {},
loading: false,
};
}
componentDidMount() {
this.loadItems();
}
loadItems() {
setTimeout(() => {
const CALENDAR_ID = 'some cal ID';
const API_KEY = 'API KEY';
const beginDate = moment();
let url = `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events?key=${API_KEY}&timeMin=${beginDate.toISOString()}&singleEvents=true&orderBy=startTime`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
const events = res.items;
if (events.length > 0) {
const newItems = {};
for (let j = 0; j < events.length; j++) {
const event = events[j];
const sTime = event.start.dateTime || event.start.date;
const eTime = event.end.dateTime || event.end.date;
const csTime = moment(sTime).format('YYYY-MM-DD');
const ceTime = moment(eTime).format('YYYY-MM-DD');
const csTime2 = moment(sTime).format('LT');
const ceTime2 = moment(eTime).format('LT');
if (!newItems[csTime]) {
newItems[csTime] = [];
}
newItems[csTime].push({
title: event.summary,
startTime: csTime2,
endTime: ceTime2,
description: event.description
})
}
this.setState({
items: newItems,
loading: false,
});
}
})
.catch(error => {
console.log('error', {error, loading: false});
});
}, 2000);
}
<FlatList
data={this.state.items}
renderItem={({ item }) => (
<View style={[styles.item, {height: item.height}]}><Text style={styles.title}>{item.title}</Text><Text>{item.startTime} - {item.endTime}</Text><Text>{item.description}</Text></View>
)}
keyExtractor={(item, index) => String(index)}
ListFooterComponent={this.renderFooter}
/>
The index is a date (2018-04-25 for example).
Why do I get this error? And what to do?
I have this code to return the address:
const geo = {
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
return response.data.results[0].formatted_address
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode'
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
return geo.getGeocode(position.coords.latitude,position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return 'Error geolocation';
},
};
export default geo;
However every time I execute
import geolocation from './geolocation';
export default class App extends Component {
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Address: {geolocation.getGeolocation()}</Text>
</View>
);
}
}
this returns the Error geolocation
It returns on console the response with the address all right
I've tried it in many ways, and within what I know it should be returning the address correctly
[EDIT]
I tried this code too:
export const geo = {
var: address = '...',
getGeocode: (latitude, longitude) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
.then(response => {
console.log(response);
response.data.results[0].formatted_address;
}).catch((error) => {
console.log( error.message )
});
return 'Error geocode';
},
getGeolocation: () => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
geo.getGeocode(position.coords.latitude, position.coords.longitude);
},
(error) => console.log( error.message ),
{ enableHighAccuracy: true, timeout: 20000 },
);
return address;
},
};
I return the address correctly, however I can not pass the value of response.data.results[0].formatted_address to variable address
How can I do this?