I'm trying to access some data input on one page by adding it to sqlite database and then displaying it on another page from the created sqlite database.
The value is not being printed, how can I check if the data is being added to the database in the first place?
I am creating a database and a table, and taking an input value on the home page and passing that to the database.
Next, I navigate to another page and display the data that was previously input from the database.
I don't know how many more details I can add.
import React, {useEffect, useState} from 'react';
import {StyleSheet, View, Text, Pressable, Alert} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import CustomButton from './utils/CustomButton';
import sqlite from 'react-native-sqlite-storage';
import {TextInput} from 'react-native-gesture-handler';
const Stack = createStackNavigator();
const db = sqlite.openDatabase(
{
name: 'MainDB',
location: 'default',
},
() => {},
error => {
console.log(error);
},
);
function ScreenA({navigation}) {
const [info, setInfo] = useState('');
useEffect(() => {
createTable();
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onPressHandler = () => {
navigation.navigate('ScreenB');
};
const createTable = () => {
db.transaction(tx => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS ' +
'Data ' +
'(ID INTEGER PRIMARY KEY AUTOINCREMENT, Info TEXT);',
);
});
};
const getData = () => {
try {
db.transaction(tx => {
tx.executeSql('SELECT Info FROM Data', [], (_tx, results) => {
var len = results.rows.length;
if (len > 0) {
navigation.navigate('ScreenB');
}
});
});
} catch (error) {
console.log(error);
}
};
const setData = async () => {
if (info.length === 0) {
Alert.alert('warning', 'please enter data');
} else {
try {
await db.transaction(async tx => {
await tx.executeSql('INSERT INTO Data (Info) VALUE (?)', [info]);
});
navigation.navigate('ScreenB');
} catch (error) {
console.log(error);
}
}
};
return (
<View style={styles.body}>
<Text style={styles.text}>hello</Text>
<TextInput
style={styles.input}
placeholer="enter your data"
onChangeText={value => setInfo(value)}
/>
<CustomButton
title="go to data"
color="#1eb900"
onPressFunction={setData}
/>
</View>
);
}
function ScreenB({navigation, route}) {
const [info, setInfo] = useState('');
const onPressHandler = () => {
navigation.navigate('ScreenA');
};
useEffect(() => {
getData();
}, []);
const getData = () => {
try {
db.transaction(tx => {
tx.executeSql('SELECT Info FROM Data'),
[],
(_tx, results) => {
let len = results.rows.length;
if (len > 0) {
let userInfo = results.rows.item(0);
setInfo(userInfo);
}
};
});
} catch (error) {
console.log(error);
}
};
return (
<View style={styles.body}>
{/* <Text style={styles.text}>Screen B</Text> */}
<Text style={styles.text}>Welcome {info} </Text>
<Pressable
onPress={onPressHandler}
style={({pressed}) => ({backgroundColor: pressed ? '#ddd' : '#0f0'})}>
{/* <Text style={styles.text}>Go Back to Screen A</Text> */}
</Pressable>
</View>
);
}
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="ScreenA" component={ScreenA} />
<Stack.Screen name="ScreenB" component={ScreenB} />
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
body: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 40,
fontWeight: 'bold',
margin: 10,
},
input: {
width: 300,
borderWidth: 1,
borderColor: '#555',
borderRadius: 10,
backgroundColor: '#ffffff',
textAlign: 'center',
fontSize: 20,
marginBottom: 10,
},
});
export default App;
I was following this tutorial on Linkedin-Learning and suddelny my code wouldn't work anymore.
Unfortunately i don't really understand these error messages:
This warning always appears:
Warning: Failed prop type: The prop onPress is marked as required in
RandomNumber, but its value is undefined.
And if I press one of the "buttons", this error messages comes up:
TypeError: _this.props.onPress is not a function. (In
'_this.props.onPress(_this.props.id)', '_this.props.onPress' is
undefined)
RandomNumber.js:
import React from "react";
import { Text, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";
class RandomNumber extends React.Component {
static propTypes = {
id: PropTypes.number.isRequired,
number: PropTypes.number.isRequired,
isDisabled: PropTypes.bool.isRequired,
onPress: PropTypes.func.isRequired,
};
handlePress = () => {
if (this.props.isDisabled) {
return;
}
this.props.onPress(this.props.id);
};
render() {
return (
<TouchableOpacity onPress={this.handlePress}>
<Text style={[styles.random, this.props.isDisabled && styles.disabled]}>
{this.props.number}
</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
random: {
backgroundColor: "#999",
width: 120,
marginHorizontal: 15,
marginVertical: 25,
fontSize: 35,
textAlign: "center",
},
disabled: {
opacity: 0.2,
},
});
export default RandomNumber;
Game.js:
import React from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import PropTypes from "prop-types";
import RandomNumber from "./RandomNumber";
import shuffle from "lodash.shuffle";
class Game extends React.Component {
static propTypes = {
randomNumberCount: PropTypes.number.isRequired,
initialSeconds: PropTypes.number.isRequired,
onPlayAgain: PropTypes.func.isRequired,
};
state = { selectedIds: [], remainingSeconds: this.props.initialSeconds };
gameStatus = "PLAYING";
randomNumbers = Array.from({ length: this.props.randomNumberCount }).map(
() => 1 + Math.floor(10 * Math.random())
);
target = this.randomNumbers
.slice(0, this.props.randomNumberCount - 2)
.reduce((acc, curr) => acc + curr, 0);
shuffledRandomNumbers = shuffle(this.randomNumbers);
componentDidMount() {
this.intervalID = setInterval(() => {
this.setState(
(prevState) => {
return { remainingSeconds: prevState.remainingSeconds - 1 };
},
() => {
if (this.state.remainingSeconds === 0) {
clearInterval(this.intervalID);
}
}
);
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
isNumberSelected = (numberIndex) => {
return this.state.selectedIds.indexOf(numberIndex) >= 0;
};
selectNumber = (numberIndex) => {
this.setState((prevState) => ({
selectedIds: [...prevState.selectedIds, numberIndex],
}));
};
UNSAFE_componentWillUpdate(nextProps, nextState) {
if (
nextState.selectedIds !== this.state.selectedIds ||
nextState.remainingSeconds === 0
) {
this.gameStatus = this.calcGameStatus(nextState);
if (this.gameStatus !== "PLAYING") {
clearInterval(this.intervalID);
}
}
}
calcGameStatus = (nextState) => {
const sumSelected = nextState.selectedIds.reduce((acc, curr) => {
return acc + this.shuffledRandomNumbers[curr];
}, 0);
if (this.state.remainingSeconds === 0) {
return "LOST";
}
if (sumSelected < this.target) {
return "PLAYING";
}
if (sumSelected === this.target) {
return "WON";
}
if (sumSelected > this.target) {
return "LOST";
}
};
render() {
const gameStatus = this.gameStatus;
return (
<View style={styles.container}>
<Text style={[styles.target, styles[`STATUS_${gameStatus}`]]}>
{this.target}
</Text>
<View style={styles.randomContainer}>
{this.shuffledRandomNumbers.map((randomNumber, index) => (
<RandomNumber
key={index}
id={index}
number={randomNumber}
onPress={this.state.selectNumber}
isDisabled={
this.isNumberSelected(index) || gameStatus !== "PLAYING"
}
/>
))}
</View>
{this.gameStatus !== "PLAYING" && (
<Button title="Play Again" onPress={this.props.onPlayAgain} />
)}
<Text>{this.state.remainingSeconds}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#ddd",
flex: 1,
},
target: {
fontSize: 40,
backgroundColor: "#bbb",
margin: 50,
textAlign: "center",
},
randomContainer: {
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "space-around",
},
STATUS_PLAYING: {
backgroundColor: "#bbb",
},
STATUS_WON: {
backgroundColor: "green",
},
STATUS_LOST: {
backgroundColor: "red",
},
});
export default Game;
App.js:
import React from "react";
import Game from "./Game";
class App extends React.Component {
state = { gameId: 1 };
resetGame = () => {
this.setState((prevState) => {
return { gameId: prevState.gameId + 1 };
});
};
render() {
return (
<Game
key={this.state.gameId}
onPlayAgain={this.resetGame}
randomNumberCount={6}
initialSeconds={10}
/>
);
}
}
export default App;
I've already tried some solutions from other posts, but none of them worked.
Any help is appreciated.
I am building a react native app that uses the Wordpress api. I am having problems displaying the cart and receive this error.
Object {} error [Error: Request failed with status code 404]
undefined
I have tried everything and have figures it might be a problem with Axios...
Please advise me on what I can do...
CartAction.js
import * as types from '../constants/ActionTypes';
import CartApi from '../api/CartApi';
export function getCart() {
return (dispatch) => {
return CartApi.getCart().then(cart => {
dispatch(getCartSuccess(cart));
}).catch(err => {
//TODO:get correct error msg
console.log(err.error);
})
};
}
function getCartSuccess(cart) {
return {
type: types.GET_CART_SUCCESS,
cart
};
}
export function addToCart(product, quantity) {
return (dispatch) => {
return CartApi.addToCart(product, quantity).then(cartUpdate => {
dispatch(addToCartSuccess(cartUpdate));
}).catch(err => {
//TODO:get correct error msg
console.log('error',err);
})
};
}
function addToCartSuccess(cartUpdate) {
return {
type: types.ADD_TO_CART_SUCCESS,
cartUpdate
};
}
CartPage.js
import React from 'react'
import { StyleSheet, Text, View, FlatList, Image } from 'react-native'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as CartAction from '../../actions/CartAction';
class CartPage extends React.Component {
constructor(props) {
super(props);
this.state = {
cart: {}
}
}
componentDidMount() {
this.props.CartAction.getCart();
}
_keyExtractor = (item, index) => item.key;
render() {
console.log(this.props.cart)
const cartObject = this.props.cart;
var cartArray = [];
Object.keys(cartObject).forEach(function(key) {
cartArray.push(cartObject[key]);
});
const Items = <FlatList contentContainerStyle={styles.list}
data={cartArray}
keyExtractor={this._keyExtractor}
renderItem={({ item }) =>
// <TouchableHighlight style={{width:'50%'}} onPress={() => navigate("Product", { product: item })} underlayColor="white">
<View style={styles.lineItem} >
<Image style={styles.image} source={{uri: item.product_image}} />
<Text style={styles.text}>{item.product_name}</Text>
<Text style={styles.text}>{item.quantity}</Text>
</View>
// </TouchableHighlight>
}
/>;
return (
<View style={styles.container}>
{Items}
</View>
)
}
}
const styles = StyleSheet.create({
lineItem: {
flexDirection: 'row'
},
list: {
flexDirection: 'column'
},
image: {
width: 50,
height: 50
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
padding: 5
}
})
function mapStateToProps(state) {
return {
cart: state.cart
};
}
function mapDispatchToProps(dispatch) {
return {
CartAction: bindActionCreators(CartAction, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CartPage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I know how to populate jSON data on FlatList and I have done that , but now here , I am populating data in between button and table data , In componentDidMount i am calling both function , first table create and then JSON call , Table data I am taking from QRCode scan from another screen and taking here .
import React, { Component } from 'react';
import { StyleSheet, View, ActivityIndicator, ScrollView } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import {Button, Text, DatePicker, Item, Picker, Input,
Textarea,FlatList} from 'native-base';
export default class OpenApplianceIssue extends Component {
constructor(props) {
super(props);
this.state = {
// tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
tableData: [], qrData: '', loading: false, selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
AbcSdata : null, loading : true,
}
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
// this.createViewGroup();
}
// componentDidMount() {
// this.createViewGroup();
// }
createViewGroup = async () => {
try {
const response = await fetch(
'http://Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
<Text style={styles.buttonText}>Id {item.inventory}</Text>
<Text>Inv {item.inventory}</Text>
<Text>Sensor {item.inventory}</Text>
</TouchableOpacity>
);
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
render() {
const state = this.state;
const AbcSdata = this.state;
if(this.state.loading == false) {
return ( <ActivityIndicator size='large' style={{height:80}} /> )
}
else {
return (
<ScrollView style={styles.container}>
<Button full rounded light style={{backgroundColor: 'blue', justifyContent: 'center', alignItems: 'center'}}
onPress={() => this.onClickListener('tag')}>
<Text style={{color: 'white'}}>Add Sensors</Text>
</Button>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
AbcSdata={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
)
}
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
try this code ..
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
export default class OpenApplianceIssue extends Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
<Text style={styles.buttonText}>Id {item.id}</Text>
<Text>Hospital Name {item.inventory}</Text>
<Text>User {item.inventory}</Text>
<Text>Date {item.inventory}</Text>
</TouchableOpacity>
);
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<TouchableOpacity full rounded light style={{backgroundColor: 'blue', justifyContent: 'center', alignItems: 'center'}}
onPress={() => this.onClickListener('tag')}>
<Text style={{color: 'white'}}>Add Sensors</Text>
</TouchableOpacity>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
alignItems: 'stretch',
fontFamily: "vincHand",
color: 'blue'
},
header_footer_style:{
width: '100%',
height: 44,
backgroundColor: '#4169E1',
alignItems: 'center',
justifyContent: 'center',
color:'#ffffff',
},
Progressbar:{
justifyContent: 'center',
alignItems: 'center',
color: 'blue',
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
textStyle:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'red',
textAlign:'center'
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
},
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
In your FlatList component you are setting AbcSdata={AbcSdata}, while you should be setting the data prop:
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
It could be because _loadInitialState in your componentDidMount is an async call and table is getting rendered initially with no data. You could try passing in some prop to refresh once you have data. Also, in the code you put here, all calls to createViewGroup() are commented out but the definition is still there. Not a big problem but still very confusing for someone looking into your code.
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;