Populating picker in react native through fetch from the server - json

I am trying to get picker values from the server to my react-native project. this is my JSON data. How do I fetch it for the picker component? I tried all d methods from web results. but I get only a blank screen. Kindly please help
{
"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
}
App.js
export default class App extends Component {
state = {
PickerValueHolder:[],
Gender:'',
}
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 PickerValueHolder = responseJson.MFBasic;
this.setState({ PickerValueHolder }); // Set the new state
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style = {styles.MainContainer}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({Gender:itemValue})} >
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.Gender} value={item.Gender} key={key}/>
)}
</Picker>}
</View>
);
}
}
above code is my app.js file. but it returns nothing to the picker.help me please. Thank u.

Looking at the json from your API call
{
"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
}
The issue that is that you are trying to set a string where it needs an array. You can do it by doing something like this:
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
let responseJson = {
"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
}
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
console.log(genderArray)
Because the items in your array are just strings you cannot access them by using item.Gender that won't work. You need to just access them using item.
I have created an example based on your code and implemented the change from above and fixed the Picker.Item component so it should render now. You can see the working code at the following snack https://snack.expo.io/#andypandy/picker-with-array-of-strings
import React from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
PickerValueHolder: [],
Gender: ''
}
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 genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
}).catch((error) => {
console.error(error);
});
}
render () {
console.log(this.state.PickerValueHolder)
return (
<View style={styles.container}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({ Gender: itemValue })} >
{ this.state.PickerValueHolder.map((item, key) =>
<Picker.Item label={item} value={item} key={key}/>
)}
</Picker>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});

Related

How to use json file fetch in react native

How should I use json data in flatlist?
This is the code I have
import React, { Component } from 'react'
import { Text, View, Button, YellowBox, FlatList, Image, ScrollView, Dimensions, TouchableHighlight } from 'react-native'
import Swiper from 'react-native-swiper'
import {styles} from '../style/styles'
class NavtexPage extends Component {
constructor(props) {//function
YellowBox.ignoreWarnings([
'Warning: componentWillReceiveProps is deprecated',
'Warning: componentWillUpdate is deprecated',
]);
super(props);
this.state = {
indexPage: 0,
isLoading: true,
}
}
//fetch API
componentDidMount = () => {
fetch('http://localhost:3000/jsondb/2',
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})//여기까지 fetch : requests
.then((response) => response.json())//fetch : response
.then((responseData) => {
console.log("성공 : ", responseData);
this.setState({
isLoading: false,
data: responseData
})
})
.catch((error) => {
console.error("api error : " + error.message);
});
}
//_renderItem how to json
_renderItem = ({ item, index }) => {
console.log('json : ', item);
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 0.1, backgroundColor: 'green' }}>
<Text>NAVTEX</Text>
</View>
<View>
<FlatList//i don't know
style={{ flex: 1, marginTop: 50, borderWidth: 1, borderColor: 'red' }}
data={this.state.data}
numColumns={1}
renderItem={this._renderItem}
// keyExtractor={(item, index) => item.no.toString()}
keyExtractor={(item => )}
/>
</View>//help
</View>
);
}
}
export default NavtexPage;
----------------------------ex.json
[
{
"Page1_1" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "asd",
"action_img" : "",
"is_ok" : "",
}
]
},
{
"Page1_2" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "Ping to 155.155.1.2 (NAVTEX TX2 at HF Site)",
"action_img" : "",
"is_ok" : "",
}
]
}
]
Firstly, you need to parse the json to array or object,then assign it to your flatlist data
.then((responseData) => {
let result = Json.parse(responseData)
// you data is array,and have page
let curPageData = result.page1_1
this.setState({
isLoading: false,
data: curPageData
})
})
You can try map function also.
sample code:-
this.state.data.map((data) => { //main data array
return(
data.map((insideData) => { //you can access page1_1 ... pages
return(
<Text>{insideData.main_subject}</Text>
.....
)
})
)
})

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}

How can i put the data array gained from the fetch return to the Dropdown component?

I'm trying to make a simple dropdown list which data is gained from a fetch return..
if I use console to view the return, it shows like this :
[
{
"ID": "BOGOR~10"
"Location": "BOGOR"
},
{
"ID": "JADETABEK~16"
"Location": "JADETABEK"
}
]
if I want to take the location BOGOR and JADETABEK and put them into a Dropdown, how can I do that? this is my testing class
import React , { Component } from 'react';
import { View , StyleSheet , Text , Dimensions } from 'react-native';
import { Dropdown } from 'react-native-material-dropdown';
const ScreenWidth = Dimensions.get('window').width;
const Screenheight = Dimensions.get('window').height;
export default class testing extends Component {
constructor(props) {
super(props)
this.state = {
data: []
}
}
componentDidMount() {
fetch(url , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"lokasi":
{
}
})
})
.then(response => response.json())
.then(res => {
this.setState({
data: res.PilihLokasiResult.Lokasi
})
alert(res.PilihLokasiResult.Lokasi)
})
}
render() {
return(
<View style={styles.container}>
<View>
<Text>{this.state.location}</Text>
<Dropdown label="select location" style={{width: 400 }}/>
</View>
</View>
)
}
}
You need to format the data since react-native-material-dropdown accepts data in the form of {value: 'Sample'}
this.state = {
data: [],
dropDownData: []
}
const formatData = (data) => {
return data.map(dataObj => {
return {value: dataObj.Location} // return based on location
})
}
.then(res => {
const dropDownData = formatData(res.PilihLokasiResult.Lokasi)
this.setState({
data: res.PilihLokasiResult.Lokasi,
dropDownData
})
})
<Dropdown label="select location" data={this.state.dropDownData} style={{width: 400 }}/>

Displaying JSON format response into React-Native

I sent a post request to the server through API upon which I received the following response in JSON format (console.log screenshot):
Upon executing the following code, I was able to Display the response in an Alert dialog box:
uploadPhoto() {
RNFetchBlob.fetch('POST', 'http://192.168.1.102:8000/api/v1/reader/', {
Authorization: 'Bearer access-token',
otherHeader: 'foo',
'Content-Type': 'multipart/form-data',
}, [
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data },
]).then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson
}, () => {
Alert.alert(" Vehicle Number Plate: " + responseJson.processed_text);
console.log(responseJson);
});
})
.catch((error) => {
console.error(error);
});
}
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.uploadPhoto.bind(this)}>
<Text style={styles.btnTextStyle}> Process Image</Text>
</TouchableOpacity>
However, Since i am very new to React-Native development, i am unable to display the JSON data in the application other than in the alert dialog box. Following is my code:
Initializing the state of jsonData object through the constructor:
constructor() {
super();
this.state = {
imageSource: null,
data: null,
jsonData: []
};
}
Thenafter, the state of jsonData object is set (In detail: Code snippet above):
.then((response) => response.json())
.then((responseJson) => {
this.setState({
jsonData: responseJson
}
Finally, I used the component FlatList for displaying the data:
<View>
<Text>Display Response JSON Data</Text>
<FlatList
data={this.state.jsonData}
renderItem={({ item }) => <Text> {item.processed_text } </Text>}
/>
</View>
However, I am not able to see the output! How can I solve this problem?
Flatlist works on arrays. Your response should be an array like this:
[
{ processed_text: 'value1', owner: { fullname: 'alex' } },
{ processed_text: 'value2', owner: { fullname: 'john' } },
]
for more insights check Flatlist

Extract data from JSON list in React native

I want to parse a JSON file and display some data on the screen. I am able to display all the data using the following code, but I want to display only entryDate and sysol. Is it possible to use a for loop in _onPressButtonGET() and display data there only?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
TouchableHighlight,
Alert,
TextInput
} from 'react-native';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import Home from './Home'
export class Temp extends Component{
constructor(props) {
super(props);
this.state = {
data: '',
data1:'',
textinput:'',
entryDate:[]
}
state={
shouldShow: false
}
}
componentDidMount(){
this._onPressButtonGET();
}
_onPressButtonPOST(){
fetch(URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"entryDate":"3/2/2017 2:00 AM",
"systol": this.state.textinput,
"mobileType":"ANDROID",
"userName":"menutest",
})})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"Blood pressure data",
"Blood pressure data - " + JSON.stringify(responseData)
)
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
}
_onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
.then((response) => response.json())
.then((responseData) => {
this.setState({ data : JSON.stringify(responseData) })
data["list"].map(d => this.state.entryDate.push(d.entryDate));
this.setState({ entryDate: jsonResponse.entryDate, systol: responseData.systol })
}).catch((error) => {
Alert.alert('problem while getting data');
})
.done();
}
render(){
return(
<View>
<TouchableHighlight onPress={this._onPressButtonPOST.bind(this)}>
<Text>Add</Text>
</TouchableHighlight>
<TouchableOpacity style= {{left:300,top:-20, }}
onPress={()=>{ this.setState({ shouldShow: !this.state.shouldShow })}}
><Text>Edit</Text></TouchableOpacity>
{this.state.shouldShow ? <TextInput placeholder='systol'
onChangeText={(text) => this.setState({textinput: text})}
/> : null}
<TouchableHighlight onPress={this._onPressButtonGET.bind(this)}>
<Text>show</Text>
</TouchableHighlight>
this.state.entryDate.map( d => (<Text>{d}</Text>));
<Text>{this.state.entryDate}</Text> //not displaying anythong
<Text>{this.state.data && JSON.parse(this.state.data)['entryDate']}</Text> //not displaying anything
<Text>hello{this.state.data}</Text> //printing all data
</View>
);
}
}
module.exports = Temp;
JSON:
{
"List": [
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
}
]
}
first initialize entryData as array
this.state = {
entryDate: [],
}
in _onPressButtonGET() use
data["List"].map(d => this.state.entryData.push(d.entryDate));
in render use map to display all data like that
this.state.entryDate.map( d => (<Text>{d}</Text>));
onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
}
.then(response => {
this.setState({entryDate:response.data})
});
renderEntryDate() {
this.state.entryDate.map((item)=>{
<Text>{item.entryDate}</Text>
})
}
render() {
return (
<View>
<Button style= {{
backgroundColor: '#6656B4',
width: 200,
height: 40,
}
onPress={() => this.onPressButtonGET()}
title="Get Weather"
color="#841584"
/>
{this.renderEntryDate()}
<View>
);
}