Extract data from JSON list in React native - json

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

Related

Fetch post API returning empty array in react native iphone app but working well in postman

I have a fetch API to get values from mysql database.Below is my screen code in which I need to get data from API:
TargetSetUpPage.js:
import React, {
useState,
useEffect,
useReducer,
useSelector,
Component,
} from "react";
import { StyleSheet, Text, Button, TextInput, ScrollView } from "react-native";
import * as authActions from "../../store/actions/auth";
const TargetSetUpPage = (props) => {
const [targetid, setTargetId] = React.useState("");
const onScreenLoad = () => {
let action;
action = authActions.getDeviceInfo();
};
useEffect(() => {
onScreenLoad();
});
return (
<ScrollView showsVerticalScrollIndicator={true}>
<Text style={styles.headingTitle}>
Set your target and start running:
</Text>
<Text style={styles.textstyle}>Target ID</Text>
<TextInput
style={styles.input}
value={targetid}
onChangeText={(targetid) => setTargetId(targetid)}
></TextInput>
<Button
title="Add"
// onPress = {() => }
/>
</ScrollView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
width: "80%",
margin: 12,
borderWidth: 1,
padding: 10,
},
headingTitle: {
fontSize: 30,
},
textstyle: {
paddingTop: 10,
fontSize: 20,
},
compact: {
flexDirection: "row",
},
buttonleft: {
paddingTop: 40,
height: 40,
width: "80%",
},
});
export default TargetSetUpPage;
Below is the store code which calls fetch API.
auth.js
import AsyncStorage from "#react-native-community/async-storage";
import Device from "../../model/Device";
export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const GETDEVICEINFO = "GETDEVICEINFO";
export const login = (textemailid, textpassword) => {
const formData = new FormData();
formData.append("txtUemail", textemailid);
formData.append("txtUpass", textpassword);
return async (dispatch) => {
fetch("https://------------------------/login.php", {
method: "post",
body: formData,
})
.then((res) => res.text())
.then((loginresult) => {})
.catch((err) => {
console.log(err);
});
const saveDataToStorage = (loginresult) => {
AsyncStorage.setItem(
"userData",
JSON.stringify({
loginresult: loginresult,
})
);
};
dispatch({ type: LOGIN });
};
};
export const logout = () => {
return { type: LOGOUT };
};
export const getUserInfo = (textemailid) => {
const formData = new FormData();
formData.append("txtEmail", textemailid);
return async (dispatch) => {
fetch("https://------------------------/getUserInformation.php", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((getuseridresult) => {
const userid = getuseridresult.map((d) => d.id);
saveDataToStorage(userid);
})
.catch((err) => {
console.log(err);
});
const saveDataToStorage = async (userid) => {
try {
await AsyncStorage.setItem(
"userDatauserid",
JSON.stringify({
userid: userid,
})
);
} catch (e) {
alert("not saved");
}
};
};
};
export const getDeviceInfo = async () => {
const useridfordevices = await AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const { userid } = obj;
var userid1 = userid[0];
console.log("txtUserId is " + userid1);
const formData = new FormData();
formData.append("txtUserId", userid1);
console.log(formData);
return async (dispatch) => {
fetch("https://-------------------------------/getDeviceInformation.php", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((result) => {
console.log("Hi" + result);
})
.catch((err) => {
console.log(err);
});
};
};
getDeviceInfo function in the above auth.js is not returning anything. I am sending correct data to fetch API as below:
txtUserId is 616718042ad26
FormData {
"_parts": Array [
Array [
"txtUserId",
"616718042ad26",
],
],
In postman I am getting the below JSON data:
[
{
"targetid": "TargetDevice1",
"targetname": "device_1",
"userid": "616718042ad26"
},
{
"targetid": "TargetDevice2",
"targetname": "device_2",
"userid": "616718042ad26"
}
]
Import and add dispatch in TargetSetUpPage:
TargetSetUpPage.js:
import React, {
useState,
useEffect,
useReducer,
useSelector,
Component,
} from "react";
import { StyleSheet, Text, Button, TextInput, ScrollView } from "react-
native";
import { useDispatch } from "react-redux";
import * as authActions from "../../store/actions/auth";
import AsyncStorage from '#react-native-community/async-storage';
const TargetSetUpPage = (props) => {
const [targetid, setTargetId] = React.useState("");
const dispatch = useDispatch();
const onScreenLoad = async() => {
const useridfordevices = await AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const { userid } = obj;
var userid1 = userid[0];
console.log("txtUserId is " + userid1);
let action;
action = authActions.getDeviceInfo(
userid1
);
await dispatch(action);
};
useEffect(() => {
onScreenLoad();
});
return (
<ScrollView showsVerticalScrollIndicator={true}>
<Text style={styles.headingTitle}>
Set your target and start running:
</Text>
<Text style={styles.textstyle}>Target ID</Text>
<TextInput
style={styles.input}
value={targetid}
onChangeText={(targetid) => setTargetId(targetid)}
></TextInput>
<Button
title="Add"
// onPress = {() => }
/>
</ScrollView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
width: "80%",
margin: 12,
borderWidth: 1,
padding: 10,
},
headingTitle: {
fontSize: 30,
},
textstyle: {
paddingTop: 10,
fontSize: 20,
},
compact: {
flexDirection: "row",
},
buttonleft: {
paddingTop: 40,
height: 40,
width: "80%",
},
});
export default TargetSetUpPage;
In the store, dispatch the action to TargetSetUpPage.js from getDeviceInfo function.
auth.js:
export const getDeviceInfo = (userid1) => {
const formData = new FormData();
formData.append("txtUserId", userid1);
return async dispatch => {
fetch('https://----------/getDeviceInformation.php',
{
method:'post',
body: formData
})
.then((res) => res.json())
.then((getuserdeviceinfo) => {
const loadDevices = [];
loadDevices.push(
new Device(
getuserdeviceinfo.map((d) => d.targetid),
getuserdeviceinfo.map((d) => d.targetname),
)
);
console.log(loadDevices);
})
.catch((err) =>{
console.log(err);
})
dispatch({type:GETDEVICEINFO,availableDevice:loadDevices})
}
}
This displays the Device array from mysql database.
Array [
Device {
"TargetId": Array [
"jtgTargetDevice1",
"jtgTargetDevice2",
],
"TargetName": Array [
"device_1",
"device_2",
],
},
]

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

Populating picker in react native through fetch from the server

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

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

Not able to parse json file and display data - react native

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: '',
textinput:'',
}
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) => {
console.error(error);
})
.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)})
}) .catch((error) => {
console.error(error);
})
.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>
<Text>{this.state.data}</Text>
</View>
);
}
}
module.exports = Temp;
I need to parse json file and display the data that is entryDate and systol. but i am not able to parse it. but in the above code i am able to display all the data.
{
"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": "121"
},
{
"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": "122"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "123"
}
]
}
this is my json file.
and i want output like:
entryDate:03/02/2017
systol:120
entryDate:03/02/2017
systol:121
entryDate:03/02/2017
systol:122
entryDate:03/02/2017
systol:123
set data state to null
this.state = {
data: null
};
change
this.setState({ data : JSON.stringify(responseData)})
to
this.setState({ data : responseData })
Then display relevant data inside your render like this -
<View>
....
....
{this.state.data &&
this.state.data.List.map((d,i) => (
<View key={i}>
<Text>{d.entryDate}</Text>
<Text>{d.systol}</Text>
</View>
))}
</View>