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

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

Related

Fetch virtual payment address of users in my react native app

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

React Native RNPicker select

i am using RNPicker Select in which i want dropdown items to get from api but i am getting empty dropdown with no values
following is my code
class Component extends Component {
constructor(props) {
super(props);
this.state = {
inqSourceList: [],
}
componentDidMount() {
this.fetchSource();
}
fetchSource = () => {
getInqSourceList('view=select', this, null)
}
<RNPickerSelect
items={this.state.inqSourceList}
name="source"
value={this.state.source ? this.state.source.id : null}
onValueChange={value => {
this.setState({
source:value,
});
}}
style={{marginBottom: 10}}
/>
and my api code is
export async function getModuleList (moduleName, params,error) {
let token = await AsyncStorage.getItem('token');
axios
.get(BASE_URL + moduleName + "?" + params, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: "Bearer " + token },
})
.then((res) => {
var bytes = CryptoJS.AES.decrypt(res.data.toString(), ENCDEC);
res.data = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
// success(res.data);
// console.log(res.data)
})
.catch(error);
}
in this i am getting values from backend when i use console.log(res.data) i get list of options..but the dropdown item is empty..
thanks
here is the function where inqSourceList is set
export function getInqSourceList(params, _this, next) {
getModuleList('settings/inquiry-source', params, data => {
_this.setState({inqSourceList: data.rows});
if (next) next(data);
});
}

React Native: setState doesn't work when calling try-catch function

I tried to call APP with this code imported from another file and it worked fine:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
let formData = new FormData();
formData.append('userId', '1'); // < this is what I want to change
formData.append('key', '***'); //my key
export function getScoreFromAPI () {
return fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
}
but now I want to change my userId from 1 to an constante from Asyncstorage, so I decide to change my code to this:
constructor(props) {
super(props)
this.state = { infos: [], userId: '' }
}
componentWillMount() {
this.getScoreFromAPI().then(data => {
this.setState({ infos: data })
});
console.log(this.state.infos);
AsyncStorage.getItem(USERID_STORED)
.then((data) => {
if (data) {
this.setState({userId:data})
}
});
}
async getScoreFromAPI() {
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
try {
let response = await fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
let res = await response.json();
} catch(error) {
console.warn("errors are " + error);
}
};
with a try-catch function but when I call getScoreFromAPI() in ComponentWillMount() I can't setState with received data, I still have an empty array in info:[]
my questions:
how can I replace '1' in userId by a value in asyncstorage in the first file ?
if it isn't possible, what I have do to setState info: [] with my data reveived
I've simplified your code into a promise chain in which calling getScoreFromAPI will execute after getting the userId from AsyncStorage, then storing the response into the infos state, while returning null if there was an error, and logging the error to the console. The data was not previously returned from getScoreFromAPI, so the value would always become null. I have not tested this code, but this should give you a good base to work from:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
export default class Test {
constructor() {
this.state = {
infos: null,
userId: ''
};
}
componentDidMount() {
AsyncStorage.getItem(this.state.userId)
.then(userID => {
this.setState({ userId: userID || '' });
})
.then(() => {
return this.getScoreFromAPI();
})
.then(data => {
this.setState({ infos: data });
})
.catch(console.error);
}
getScoreFromAPI = () => {
const formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(response => {
// use response data here
return response.json();
})
.catch(e => {
console.error(e);
return null;
});
};
}
You're doing your API call before fetching your value from AsyncStorage (I know this is async but it's not very readable if you do it that way).
getScoreFromAPI doesn't return anything, that's why your setState isn't working.
You don't need to use try and catch here, promises have their own error handling mechanism (the .catch() method).
I think callbacks are more readable and lead to less bugs than using .then() in code.
This is how I would do it:
constructor(props)
{
super(props);
this.state = { infos: [], userId: '' };
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentWillMount()
{
// Get userID from local storage, then call your API
AsyncStorage.getItem(YOUR_KEY)
.then(userID=> {
if (userID)
{
this.setState({ userId : userID }, () => {
this.getScoreFromAPI(this.onSuccess, this.onFailure);
});
}
});
}
onSuccess(data)
{
this.setState({
infos : data
});
}
onFailure(err)
{
console.warn('Error ' + err);
}
getScoreFromAPI(onSuccess, onFailure)
{
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //your key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(res => res.json())
.then(json => {
onSuccess(json);
})
.catch(err => {
onFailure(err);
});
}
It's finally done. I tried this and it worked. Thank you to all of you
this is what I have done:
...
const USERID_STORED = "userid_stored";
const GSM_STORED = "gsm_stored";
...
class ScoreList extends React.Component {
constructor(props) {
super(props)
this.state = { infos: [], userId: '', gsmStored: '', }
}
componentWillMount() {
AsyncStorage.getItem(USERID_STORED)
.then(userId => {
this.setState({ userId: userId});
this.getScoreFromAPI(this.state.userId).then(data => {
this.setState({ infos: data });
});
});
AsyncStorage.getItem(GSM_STORED)
.then(gsmStore => {
this.setState({ gsmStored: gsmStore});
});
}
getScoreFromAPI (userId) {
let formData = new FormData();
formData.append('userId', userId);
formData.append('key', '***');
return fetch('https://***',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
};

fetching values from server for multiselect picker react native

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

Getting Undefined in React native

import React, { Component } from 'react';
import { View, Text } from 'react-native';
class HttpExample extends Component {
state = {
data: ''
}
componentDidMount = () => {
fetch("https://jsonplaceholder.typicode.com/posts/1", { --this is fake url
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
}),
body: "param1=value1&param2=value2" // <-- Post parameters
})
.then((response) =>
response.text()
)
.then((responseText) => {
alert(responseText.id);
this.setState({
data: responseText
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>
{this.state.data.id}
</Text>
</View>
)
}
}
export default HttpExample;
if i use alert(ResponseText)
in alert i am getting o/p but as i tried to have individual value from my object it returns undefined
o/p: "id": "1",
"computeId": "USR00001" in alert
.then((response) => response.text())
to
.then((response) => response.json())
I guess you need json style response.