I want to get specific the first two elements from a webservice and print it to a console it is returning me 1000 items. Can anyone guide me on how I can print only the first two elements
import React from "react";
import {StyleSheet,View,ActivityIndicator,FlatList,Text,TouchableOpacity} from "react-native";
export default class Source extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Source Listing",
headerStyle: {backgroundColor: "#fff"},
headerTitleStyle: {textAlign: "center",flex: 1}
};
};
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.email}</Text>
<Text style={styles.lightText}>{data.item.company.name}</Text>
</TouchableOpacity>
render(){
{
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}}
return(
<View style={styles.container}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
const parseString = require('react-native-xml2js').parseString;
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
console.log(response[0],response[1])
});
}).catch((err) => {
console.log('fetch', err)
})
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 4,
margin: 5,
backgroundColor: "#fff"
}
});
I want it to be print on the console then I will modify it later to display it on the app. I am struggling to get this done Please help
You are parsing the response as string. If you want to print the first two item in console, you can do it like this bellow:
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then((response) => {
console.log(response.data[0],response.data[1])
}).catch((err) => {
console.log('fetch', err)
})
Perhaps what you need is the result?
parseString(response, function (err, result) {
console.log(result) // not console.log(response)?
});
Using JavaScript
fetch("http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master")
.then((r) => r.text())
.then((t) => (new window.DOMParser()).parseFromString(t, "text/xml"))
.then((d) => console.log(d))
.catch((e) => console.error(e));
Related
I'm working on flatlist with checkbox but could not select multiple checkboxes inside flatlist. Every time only single item is selected. Wanted to add dynamic checkbox according to the list and have to handle all checkbox using one function. I have used the following code but its not working. Any help would be appreciated.
import React, { useState, useEffect } from 'react';
import {
SafeAreaView,
StyleSheet,
Text,
View,
FlatList,
TouchableOpacity,
Image,
ActivityIndicator,
} from 'react-native';
import CheckBox from '#react-native-community/checkbox';
const App = () => {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
getListPhotos();
return () => {
}
}, [])
getListPhotos = () => {
const apiUrl = 'https://jsonplaceholder.typicode.com/photos';
fetch(apiUrl)
.then((res) => res.json())
.then((resJson) => {
setData(resJson);
}).catch((err) => { console.error('Error', err); })
.finally(() => setIsLoading(false))
}
onChangeValue = (item, index) => {
const newData = data.map(newItem => {
if (newItem.id == item.id) {
return {
...newItem,
selected: true,
}
}
return {
...newItem,
selected: false,
}
})
setData(newData);
}
renderItem = ({ item, index }) => {
return (
<View style={styles.item}>
<Image style={styles.image}
source={{ uri: item.url }}
resizeMode='contain'
/>
<View style={styles.wrapText}>
<Text >{item.title}</Text>
<CheckBox
value={item.selected}
style={styles.ckItem}
disabled={false}
onAnimationType='fill'
offAnimationType='fade'
boxType='square'
onValueChange={() => onChangeValue(item, index)}
/>
</View>
</View>
)
}
return (
<SafeAreaView style={styles.container}>
{isLoading ? <ActivityIndicator /> : (<FlatList
style={styles.list}
data={data}
renderItem={renderItem}
//keyExtractor={(item, index) => item.id}
keyExtractor={item => `key-${item.id}`}
/>)}
<View>
<Text style={styles.wrapButton}></Text>
<TouchableOpacity style={styles.button}>
<Text>
Show item you selected
</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
list: {
flex: 1,
padding: 8,
},
wrapButton: {
width: '100%',
justifyContent: 'center',
alignItems: 'center',
},
button: {
padding: 16,
backgroundColor: 'orange',
// justifyContent:'center',
// alignItems:'center',
alignSelf: 'center',
width: '50%'
},
item: {
marginTop: 8,
flexDirection: 'row',
padding: 4,
shadowColor: '#000',
shadowOffset: {
width: 0, height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
image: {
width: 100,
height: 150,
},
wrapText: {
flex: 1,
marginTop: 16,
marginLeft: 8,
},
ckItem: {
width: 20,
height: 20,
marginTop: 5,
},
});
export default App;
onValueChange={newValue => onChangeValue(item, index, newValue)}
onChangeValue = (item, index, newValue) => {
const newData = data.map(newItem => {
if (newItem.id == item.id) {
return {
...newItem,
selected: newValue,
}
}
return newItem
})
setData(newData);
}
You can achieve by using below plugins
https://bestofreactjs.com/repo/tableflip-react-native-select-multiple-react-react-native-awesome-components
https://github.com/vakiller/react-native-flatlist-multiple-choose/blob/master/readme.md
Hi I am new to react native i am facing this error TypeError:undefined is not an object (evaluating this.state.items)
Another problem is it is returning me the data in an array how do i display the data as a string
import React, { Component } from "react";
import {StyleSheet,View,ActivityIndicator,FlatList,Text,TouchableOpacity} from "react-native";
export default class Source extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Source Listing",
headerStyle: {backgroundColor: "#fff"},
headerTitleStyle: {textAlign: "center",flex: 1}
};
};
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
this.fetchRequest=this.fetchRequest.bind.this
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
componentDidMount()
{
fetchRequest();
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.email}</Text>
<Text style={styles.lightText}>{data.item.company.name}</Text>
</TouchableOpacity>
render(){
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
fetchRequest()
{
const parseString = require('react-native-xml2js').parseString;
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
console.log(response)
});
}).catch((err) => {
console.log('fetch', err)
this.fetchdata();
})
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}}
return(
<View style={styles.container}>
</View>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 4,
margin: 5,
backgroundColor: "#fff"
}
});
Basically what i am trying to do is to get data from webservices and display the app on the screen
Hi I need help as to how do i get a specific value from an array in a web service i am using fetch method to get the data.It is in XML i am using a dependency to convert xml data to JSON.
import React from "react";
import {StyleSheet,View,ActivityIndicator,FlatList,Text,TouchableOpacity} from "react-native";
export default class Source extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Source Listing",
headerStyle: {backgroundColor: "#fff"},
headerTitleStyle: {textAlign: "center",flex: 1}
};
};
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.email}</Text>
<Text style={styles.lightText}>{data.item.company.name}</Text>
</TouchableOpacity>
render(){
{
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}}
return(
<View style={styles.container}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
const parseString = require('react-native-xml2js').parseString;
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
console.log(response)
});
}).catch((err) => {
console.log('fetch', err)
this.fetchdata();
})
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 4,
margin: 5,
backgroundColor: "#fff"
}
});
I am pretty new to react native and development in general i would highly apprecitate any help .I need to seprate the elements and display specific elements in the app.
As far as I can tell from your code, you are not passing the fetched data into your state. You're only logging it in the console:
parseString(response, function (err, result) {
console.log(response)
});
I think you should add the following pieces to your component:
1 . First of all set up the function to be called in your constructor, so it can access the state:
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
this.fetchRequest = this.fetchRequest.bind(this)
}
Create the actual function inside render:
fetchRequest() {
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
this.setState({ items: response });
});
}).catch((err) => {
console.log('fetch', err)
})
}
You need to call the fetchRequest function. You can do that in a lifecycle method of your component:
componentDidMount() {
fetchRequest();
}
Last thing is to create your Flatlist correctly:
<FlatList
data= {this.state.items}
renderItem={({ item }) => <Item title={item.title} />}
keyExtractor= {item=>item.id.toString()}
/>
Your data source is this.state.items, and not this.state.dataSource.
Unfortunately I have no idea what your data looks like, so I don't know how the keyExtractor and <Item> should be written. What I can tell you is that you will need unique IDs for your items.
You can read more about Flatlist in the React Native docs.
I have a list of articles which is fetching from server(json).There will be two server calls.What I meant is now I'm listing some article title (fetching from server1) within a Card.Below that there will be an add button for copy and pasting new article links(that will be saved to a different server).So I'm trying to append this newly added articles to my existing list(just like the same in pocket app).How can I do this?I've tried something like the below.But I'm getting error , may be a little mistake please help me to figure out.Since the render should happen only after button click(for viewing newly added ones).So state will also set after that right?How can I do that?
import {article} from './data'; //json
import AddNewarticle from './AddNewarticle';
class SecondScreen extends Component {
state= {
newarticle: []
};
// request for saving newly added article
onPressSubmit(){
fetch('www.mywebsite.com',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
url: this.state.url,
})
})
.then(response => response.json())
.then((responseData) => this.setState({newarticle: responseData}));
}
renderArticle(){
this.state.newarticle.message.map(newlist =>
<AddNewarticle key ={newlist.title} newlist={newlist} />
);
}
render(){
return(
<ScrollView>
{article.map(a =>
<CardSection>
<Text>
{a.title}</Text>
</CardSection>
{this.renderArticle()}
</ScrollView>
<Icon
raised
name="check"
type="feather"
color="#c1aba8"
iconStyle={{ resizeMode: "contain" }}
onPress={() => {
this.onPressSubmit();
}}
/>
);
}
Also my newarticle (json) is as follows.The response I'm getting from server after submitting new articles.
{
"message": {
"authors": [
"Zander Nethercutt"
],
"html": "<div><p name=\"c8e3\" id=\"c8e3\" class=\"graf graf--p graf--hasDropCapModel graf--hasDropCap graf--leading\">The presence of advertising in This is the power of branding.",
"title": "The Death of Advertising – Member Feature Stories – Medium"
},
"type": "success"
}
The error I'm getting is newarticle is not defined.
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert,Image, Platform } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
GetItem (flower_name) {
Alert.alert(flower_name);
}
componentDidMount() {
return fetch('https://reactnativecode.000webhostapp.com/FlowersList.php')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) =>
<View style={{flex:1, flexDirection: 'row'}}>
<Image source = {{ uri: rowData.flower_image_url }} style={styles.imageViewContainer} />
<Text onPress={this.GetItem.bind(this, rowData.flower_name)} style={styles.textViewContainer} >{rowData.flower_name}</Text>
</View>
}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
// Setting up View inside content in Vertically center.
justifyContent: 'center',
flex:1,
margin: 5,
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
},
imageViewContainer: {
width: '50%',
height: 100 ,
margin: 10,
borderRadius : 10
},
textViewContainer: {
textAlignVertical:'center',
width:'50%',
padding:20
},
tabIcon: {
width: 16,
height: 16,
}
});
AppRegistry.registerComponent('App', () => App);
export default App;
I want to develop a React Native app, and I want to have locally stored some data of the format:
[
{
"id": 1,
"text": "Lorem ipsum",
"viewed": false
},
{
"id": 2,
"text": "Second lorem",
"viewed": false
},
{
"id": 3,
"text": "Last lorem",
"viewed": false
}
]
I want this data to be available when the user first downloads the app. Then based on the user's navigation, the corresponding data in the db will change the viewed flag to true. This has to be persistent when the app will be updated by the user on the next version.
Any tips/ideas on how to achieve this?
Currently I'm looking into Realm.io but I'm not sure if this is the right tool for me.
You can use AsyncStorage for that like so:
const data = [
{
"id": 1,
"text": "Lorem ipsum",
"viewed": false
},
{
"id": 2,
"text": "Second lorem",
"viewed": false
},
{
"id": 3,
"text": "Last lorem",
"viewed": false
}
]
try {
await AsyncStorage.setItem(
'SOME_KEY', JSON.stringify(data)
);
} catch (error) {
// Handle error
}
Later on if you want to fetch/change you can do:
AsyncStorage.getItem('SOME_KEY', (err, result) => {
console.log(JOSN.parse(result));
});
If data is more than pouchDb is suggested option.
You can install it with
npm install pouchdb-react-native --save
Simple Demo
import PouchDB from 'pouchdb-react-native'
const db = new PouchDB('mydb')
// use PouchDB
db.get('4711')
.then(doc => console.log(doc))
Advance Demo
'use strict'
import React from 'react'
import {
AsyncStorage,
ListView,
Navigator,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View
} from 'react-native'
import ActionButton from 'react-native-action-button'
import PouchDB from 'pouchdb-react-native'
const localDB = new PouchDB('myDB')
console.log(localDB.adapter)
AsyncStorage.getAllKeys()
.then(keys => AsyncStorage.multiGet(keys))
.then(items => console.log('all pure Items', items))
.catch(error => console.warn('error get all Items', error))
export default React.createClass({
getInitialState () {
const updateDocs = () => {
localDB.allDocs({include_docs: true, limit: null})
.then(result => {
const items = result.rows.map(row => row.doc)
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id})
this.setState({
dataSource: ds.cloneWithRows(items),
count: items.length
})
})
.catch(error => console.warn('Could not load Documents', error, error.message))
}
localDB.changes({since: 'now', live: true})
.on('change', () => updateDocs())
updateDocs()
return {
dataSource: null,
syncUrl: 'http://localhost:5984/test'
}
},
render () {
const renderScene = (route, navigator) => (
<View style={{flex: 1, marginTop: 20, backgroundColor: '#FFFFFF'}}>
{route.render()}
</View>
)
const renderMain = () => {
const insertAttachment = () => {
const doc = {
'title': 'with attachment',
'_attachments': {
'att.txt': {
'content_type': 'text/plain',
'data': 'TGVnZW5kYXJ5IGhlYXJ0cywgdGVhciB1cyBhbGwgYXBhcnQKTWFrZS' +
'BvdXIgZW1vdGlvbnMgYmxlZWQsIGNyeWluZyBvdXQgaW4gbmVlZA=='
}
}
}
localDB.post(doc)
.then(result => console.log('save.attachment', result))
.catch(error => console.warn('save.attachment.error', error, error.message, error.stack))
}
const insertRecords = count => {
for (let index = 0; index < count; index++) {
localDB.post({
text: `Record ${index}/${count}`
})
}
}
const destroy = count => {
localDB.destroy()
.then(() => console.log('destroyed'))
.catch(error => console.warn('destroyed', error))
}
const { dataSource } = this.state
const renderSeparator = (sectionID, rowID) => (
<View
key={rowID}
style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
)
const renderRow = (row) => {
const updateItem = () => {
const newRow = {...row}
newRow.clickCount = newRow.clickCount ? newRow.clickCount + 1 : 1
localDB.put(newRow)
.then(result => console.log('Updated Item', result))
.catch(error => console.warn('Error during update Item', error))
}
return (
<TouchableHighlight onPress={updateItem}>
<View key={row._id}>
<Text style={{fontWeight: 'bold'}}>{row._id}</Text>
<Text>{JSON.stringify(row, null, 4)}</Text>
</View>
</TouchableHighlight>
)
}
const renderList = () => (
<ListView
dataSource={dataSource}
renderRow={renderRow}
renderSeparator={renderSeparator}
enableEmptySections />
)
return (
<View style={{flex: 1}}>
<View>
{!!this._sync && <Text style={{fontWeight: 'bold'}}>{this.state.syncUrl}</Text>}
<Text style={{fontWeight: 'bold'}}>Count: {this.state.count}</Text>
</View>
<View
style={{borderColor: '#969A99', borderBottomWidth: StyleSheet.hairlineWidth}} />
{!dataSource
? (<Text>Loading...</Text>)
: renderList()
}
<ActionButton buttonColor='#78B55E'>
<ActionButton.Item
buttonColor='#005BFF'
title='Destroy Database'
onPress={destroy}>
<Text>destroy</Text>
</ActionButton.Item>
<ActionButton.Item
buttonColor='#005BFF'
title='Insert Attachments'
onPress={insertAttachment}>
<Text>attach</Text>
</ActionButton.Item>
<ActionButton.Item
buttonColor='#005BFF'
title='Insert 250 Records'
onPress={() => insertRecords(250)}>
<Text>insert</Text>
</ActionButton.Item>
<ActionButton.Item
buttonColor='#005BFF'
title='Sync'
onPress={() => this._navigator.push({name: 'Sync', render: renderSync})}>
<Text>sync</Text>
</ActionButton.Item>
<ActionButton.Item
buttonColor='#005BFF'
title='Add Item'
onPress={() => this._navigator.push({name: 'AddItem', render: renderAddItem})}>
<Text>+</Text>
</ActionButton.Item>
</ActionButton>
</View>
)
}
const renderButton = (text, onPress) => {
return (
<TouchableHighlight
onPress={onPress}
style={{
flexDirection: 'column',
paddingTop: 3,
paddingBottom: 3,
marginLeft: 10,
marginRight: 10,
backgroundColor: '#78B55E',
borderRadius: 5
}}>
<Text
style={{
flex: 1,
fontSize: 18,
fontWeight: 'bold',
color: '#FFFFFF',
paddingLeft: 10,
paddingRight: 10,
paddingTop: 2,
alignSelf: 'center'
}}>
{text}
</Text>
</TouchableHighlight>
)
}
const renderSync = () => {
const addSync = () => {
if (this._sync) {
this._sync.cancel()
this._sync = null
}
if (this.state.syncUrl) {
const remoteDb = new PouchDB(this.state.syncUrl, {ajax: {cache: false}})
this._sync = PouchDB.sync(localDB, remoteDb, {live: true, retry: true})
.on('error', error => console.error('Sync Error', error))
.on('change', info => console.log('Sync change', info))
.on('paused', info => console.log('Sync paused', info))
}
this._navigator.pop()
}
return (
<View style={{flex: 1}}>
<TextInput
style={{
height: 40,
lineHeight: 40,
fontSize: 16,
paddingLeft: 10,
paddingRight: 10
}}
autoFocus
keyboardType='url'
clearButtonMode='always'
placeholder='enter URL'
onChangeText={(text) => this.setState({syncUrl: text})}
value={this.state.syncUrl} />
{renderButton('Add Sync', addSync)}
</View>
)
}
const renderAddItem = () => {
const addItem = () => {
localDB.post(JSON.parse(this.state.newItem))
.then(result => {
this.setState({newItem: ''})
this._navigator.pop()
})
.catch(error => console.error('Error during create Item', error, error.message))
}
return (
<View style={{flex: 1}}>
<TextInput
style={{
height: 340,
lineHeight: 40,
fontSize: 16,
paddingLeft: 10,
paddingRight: 10
}}
autoFocus
clearButtonMode='always'
multiline
placeholder='JSON Object here'
onChangeText={(text) => this.setState({newItem: text})}
value={this.state.newItem} />
{renderButton('Add Item', addItem)}
</View>
)
}
return (
<View style={{flex: 1}}>
<Navigator
ref={navigator => { this._navigator = navigator }}
renderScene={renderScene}
initialRoute={{name: 'Main', render: renderMain}}
/>
</View>
)
}
})