I am developing react native application where I wanted to show some loader before loading screen,
I have different component for Loader and different component to load data,
In Loader component I hava a field isVisible (true/false) like below
constructor(props) {
super(props);
this.state = {
index: 0,
types: ['CircleFlip', 'Bounce', 'Wave', 'WanderingCubes', 'Pulse', 'ChasingDots', 'ThreeBounce', 'Circle', '9CubeGrid', 'WordPress', 'FadingCircle', 'FadingCircleAlt', 'Arc', 'ArcAlt'],
size: 100,
color: "#ff0000",
isVisible: true
}
render() {
var type = this.state.types[this.state.index];
return (
<View style={styles.container}>
<Spinner style={styles.spinner} isVisible={this.state.isVisible} size={this.state.size} type={'ThreeBounce'} color={this.state.color}/>
</View>
);
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
// backgroundColor: '#d35400',
},
spinner: {
marginBottom: 50
},
btn: {
marginTop: 20
},
text: {
color: "white"
}
});
and in Other Component where I am rendering my view after getting data from api.
constructor(props) {
super(props);
this.state = {
tableHead: ['Form Name', 'Download'],
tableData: [],
isVisible:true
}
}
componentDidMount(){
dataSourceRes =getDocumentList(function(dataSourceRes){
var tableDataRows=[];
for(let i = 0; i < dataSourceRes.length; i++){
var arr=[];
arr.push(dataSourceRes[i].docName, dataSourceRes[i].docPath);
tableDataRows.push(arr);
}
this.setState({
tableData : tableDataRows
});
}.bind(this));
};
render() {
const state = this.state;
const element = (data, index) => (
<TouchableOpacity onPress={() => this._alertIndex(data)}>
<View style={styles.btn}>
<Text style={styles.btnText}>Download</Text>
</View>
</TouchableOpacity>
);
return (
<View style={styles.container}>
<Loader></Loader>
{/* <Loader> */}
<ScrollView>
<Table borderStyle={{borderColor: 'transparent'}}>
<Row data={state.tableHead} style={styles.head} textStyle={styles.textHeader}/>
{
state.tableData.map((rowData, index) => (
<TableWrapper key={index} style={styles.row}>
{
rowData.map((cellData, cellIndex) => (
<Cell key={cellIndex} data={cellIndex === 1 ? element(cellData, index) : cellData} textStyle={styles.text}/>
))
}
</TableWrapper>
))
}
</Table>
</ScrollView>
{/* </Loader> */}
</View>
)
}
}
Please let me know the solution how to resolve it
You could do as follows
class Foo extends React.Component {
constructor(props) {
this.state = { loading: true };
}
componentDidMount() {
// Fetch data then set state
fetch(something).then(() => this.setState({ loading: false }));
}
render() {
if (this.state.loading) {
return <Loader/>;
}
return <MyComponent/>;
}
}
After fetched data from api then send isvisibility false to loader component
Related
I'm new to react. I have my App.js page that contains the main code, and a lists.js page in another folder that contains the list itself.
I import from lists.js into my App.js. It works fine.
I'm trying to set an onPress action for the listItems that also sends a unique ID to the next page that I can use to call out items in the new page.
For clarity, if i was to do this with a normal button, it will look like:
this.props.navigation.navigate('NextPage', { Email: UserEmail });
So how do i do this with a ListView that I imported from another file.
This is how my code is structured
App.js
import MarketList from './lists/markets';
class ProfileActivity extends Component
{
static navigationOptions =
{
title: 'Home',
headerStyle : {
backgroundColor: '#00b47a'
},
headerTitleStyle: {
color: 'white'
},
headerLeft: null,
headerRight: (
<Icon containerStyle={{ paddingRight: 15 }}
color='#000' onPress={()=> navigation.getParam('openBottomSheet')()}
name="menu" />
)
};
constructor () {
super()
this.state = { toggled: false }
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<MarketList />
</View>
);
}
}
My lists.js
export default class MarketList extends React.Component {
constructor(props) {
super(props)
this.state = {
items: '',
};
}
render() {
fetch('https://example.php')
.then((response) => response.json())
.then((json) => {
this.setState({
items: json.items,
})
})
.catch((error) => {
console.error(error);
});
return (
<View style={styles.container}>
<FlatList
data={this.state.items}
renderItem={({item}) => <TouchableOpacity onPress={} style={styles.itemList}><View style={styles.item}><Text style={styles.market}>{item.name}</Text><Text style={styles.location}>{item.Location}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></TouchableOpacity>}
/>
</View>
);
}
}
You can do something like below
Pass navigation as a prop to MarketList component
<MarketList navigation={this.props.navigation}/>
And use like below
renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("pagename",{item:item})}
I am working on a task in which I have to implement infinite scroll paging of 600 dummy records to cards I have coded on FlatList render. So far I have implemented logic using FlatList but not successfully. Help is required where I am doing wrong thus not giving result. Here is the component code:
import React, { Component } from "react";
import { StyleSheet, ActivityIndicator, FlatList, View } from "react-native";
import { Card } from "react-native-elements";
class InfiniteScroll extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: [],
dummy: [],
fetchingStatus: false,
setOnLoad: false,
};
this.page = 0;
let onEndReached = false;
}
componentDidMount() {
var toput = [];
for (let i = 0; i < 598; i++) {
toput.push({
name: "KHAN MARKET",
order_no: "ORDER # DBZ-876",
status: "Order Completed",
price: "Total: $14.00",
date: "Dec 19, 2019 2:32 PM",
});
}
this.setState(
{
dummy: toput,
},
() => {
console.log(this.state.dummy);
}
);
this.apiCall();
}
apiCall = () => {
var that = this;
var old = that.page;
that.page = that.page + 10;
console.log(" *********** call " + this.page);
that.setState({ fetchingStatus: true });
that.setState({
data: [...this.state.data, ...this.state.dummy.slice(old, that.page)],
isLoading: false,
fetchingStatus: false,
setOnLoad: true,
});
};
BottomView = () => {
return (
<View>
{this.state.fetchingStatus ? (
<ActivityIndicator
size="large"
color="#F44336"
style={{ marginLeft: 6 }}
/>
) : null}
</View>
);
};
ItemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: "100%",
backgroundColor: "#607D8B",
}}
/>
);
};
render() {
return (
<View>
{this.state.isLoading ? (
<ActivityIndicator size="large" />
) : (
<FlatList
style={{ width: "100%" }}
keyExtractor={(item, index) => index}
data={this.state.data}
ItemSeparatorComponent={this.ItemSeparator}
onScrollEndDrag={() => console.log(" *********end")}
onScrollBeginDrag={() => console.log(" *******start")}
initialNumToRender={8}
maxToRenderPerBatch={2}
onEndReachedThreshold={0.1}
onMomentumScrollBegin={() => {
this.onEndReached = false;
}}
onEndReached={() => {
if (!this.onEndReached) {
this.apiCall(); // on end reached
this.onEndReached = true;
}
}}
renderItem={({ item, index }) => (
<View>
<Card>
<Text
style={{ justifyContent: "flex-start", fontWeight: "bold" }}
>
{item.name}
</Text>
<View style={styles.textview}>
<Text style={styles.orderno}>{item.order_no}</Text>
<Text style={styles.orderstatus}>{item.status}</Text>
</View>
<Text style={styles.amount}>{item.price}</Text>
<View style={styles.textview}>
<Text style={styles.orderno}>{item.date}</Text>
</View>
</Card>
</View>
)}
ListFooterComponent={this.BottomView}
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
textview: {
marginTop: 5,
flexDirection: "row",
justifyContent: "space-between",
},
orderno: {
flexDirection: "row",
justifyContent: "flex-start",
},
orderstatus: {
flexDirection: "row",
justifyContent: "flex-end",
color: "green",
},
ordercomplete: {
flexDirection: "row",
justifyContent: "flex-end",
color: "red",
},
amount: {
justifyContent: "flex-start",
marginTop: 5,
},
});
export default InfiniteScroll;
I will be very thankful if you can provide solution. Thanks
The thing here is that you are seting your dummy data and calling the apiCall next, the dummy data is not updated yet when you call the apiCall, ande the dummy data is shown as an empty array on the apiCall, you just ned to force some await before calling the function, just change from this:
this.setState(
{
dummy: toput,
},
() => {
console.log(this.state.dummy);
}
);
this.apiCall();
to this:
this.setState(
{
dummy: toput
},
() => {
this.apiCall();
}
);
Another thing I notice is that you are using some bad pratices like setting valuse direct on the class instead of using state and some messing with the scope (that = this), I've made some updates/suggestions in you code that may help with readability:
apiCall = () => {
const newPage = this.state.page + 10;
this.setState({
data: [
...this.state.data,
...this.state.dummy.slice(this.state.page, newPage)
],
isLoading: false,
fetchingStatus: false,
setOnLoad: true,
page: newPage
});
};
I've created a fully working example so you can see some more updates I've made in the code, that may help you as well:
https://codesandbox.io/s/stackoverflow-67166780-321ku?file=/src/App.js
I'm new to React native and development in general and am trying to retrieve data from an webservice and then render it but I seem to be running into different errors.
I am getting this error
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(){
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}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
<FlatList
data={this.state.items}
renderItem={({ item }) => <Item title={item.title} />}
keyExtractor= {item=>item.id.toString()}
/>
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"
}
});
The main cause what i am trying to achieve is render the 'items' that are returned from the webservice.
Kindly guide me with this error
i have two components one is called homeScreen the second is card i do fetch data in homeScreen i set it to state after i do send state through props to my card component .
Now my card components should generate 9 cards accoridng to the data i am sending through to it so i did map and i am getting this error
TypeError: Cannot read property '0' of undefined.
i tried to console.log props inside Card component and i could see data but for some reason the map isnt working
Card.js
const Card = props => {
Array.from({length: 9}).map((i, index) => {
console.log(props);
return (
<View style={{flex: 1}}>
<Text style={{flex: 1, backgroundColor: 'red'}}>
{props.title[1] ? `${props.title[index]}` : 'Loading'}
</Text>
<Text style={{flex: 1, backgroundColor: 'blue'}}>{props.rating[index]}</Text>
</View>
);
});
};
export default Card;
homeScreen.js
export default class HomeScreen extends React.Component {
state = {
title: [],
image: [],
rating: [],
isLoading: true,
};
componentDidMount() {
this.getData();
}
titleSend = () => {
if (!this.state.isLoading) {
{
Array.from({length: 9}).map((i, index) => {
return this.state.title[index];
});
}
}
};
imageSetter = () => {
Array.from({length: 9}).map((i, keys) => {
return (
<Image
key={keys}
style={{width: 50, height: 50, flex: 1}}
source={{uri: this.state.image[keys]}}
/>
);
});
};
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
const shows = data.map(show => show.data);
this.setState({
isLoading: false,
title: shows.map(show => show.name),
image: shows.map(show => show.image.medium),
rating: shows.map(show => show.rating.average),
});
// console.log(this.state);
};
const handleError = error => {
this.setState({
isLoading: false,
});
};
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, title, image, rating} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ScrollView style={{flex: 1, backgroundColor: 'red'}}>
<Card title={this.state.title} />
</ScrollView>
<Text>here images</Text>
</View>
);
}
}
None of your functions/methods using Array.from are returning a value.
For example your Card component:
const Card = props => {
// note addition of `return` statement
return Array.from({length: 9}).map((i, index) => {
console.log(props);
return (
<View style={{flex: 1}}>
<Text style={{flex: 1, backgroundColor: 'red'}}>
{props.title[1] ? `${props.title[index]}` : 'Loading'}
</Text>
<Text style={{flex: 1, backgroundColor: 'blue'}}>{props.rating[index]}</Text>
</View>
);
});
};
export default Card;
The titleSend and imageSetter methods have a similar issue.
The index error is because you're not passing an rating prop to the Card component but you're accessing props.rating[0], props.rating[1], etc.
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ScrollView style={{flex: 1, backgroundColor: 'red'}}>
// missing `rating` prop
<Card title={this.state.title} />
</ScrollView>
<Text>here images</Text>
</View>
);
Im pretty new in React Native (and Javscript) and im trying to understand react native navigation.
I have a homeScreen, and in this screen there is a CardFlatList, which has several CardComponents. If i click on a CardComponent, a Detail Page should open and represent the information of the cardComponent.
First I tried the navigation with a button in the homeScreen and it worked. But i don't know how to pass the navigator from homescreen -> CardFlatList -> CardComponent (onPress).
My CardComponent
export default class CardComponent extends Component {
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.container}>
<Card
featuredTitle={this.props.eventname}
featuredSubtitle={this.props.eventveranstalter}
image={{uri: this.props.eventimage}}
>
<View style={styles.chipContainer}>
<ChipsComponent text={this.props.eventtag1} style={{ marginBottom: 10 }} />
<ChipsComponent text={this.props.eventtag2} style={{ marginBottom: 10 }} />
<ChipsComponent text={this.props.eventtag3} style={{ marginBottom: 10 }} />
</View>
<View style={styles.cardaction}>
<Text style={styles.cardfooter}>
{this.props.eventuhr}
</Text>
<Text style={styles.cardfooter}>
{this.props.eventort}
</Text>
<Button
backgroundColor='#5ac8fa'
fontFamily='Arial'
fontWeight='bold'
buttonStyle={styles.buttonfooter}
title='Teilnehmen' />
</View>
</Card>
</View>
)
}
My homeScreen
export default class homeScreen extends Component {
static navigationOptions = {
drawerLabel: 'Home',
headerMode: 'none',
};
constructor(props) {
super(props)
}
render() {
var {navigate} = this.props.navigation;
return (
<View style={styles.containerAll}>
<Navigationbar onPressBar={()=>this.props.navigation.navigate('DrawerOpen')} />
<View style={styles.container}>
<CardFlatList navigation={this.props.navigation} />
</View>
</View>
);
}
}
my router.js
export const DrawNavigation = DrawerNavigator({
Home: {
screen: homeScreen
},
Notifications: {
screen: test,
},
});
export const Root = StackNavigator({
DrawNavigation: {
screen: DrawNavigation,
navigationOptions: {
header: false,
},
},
First: { screen: homeScreen },
Second: { screen: eventDetailScreen },
});
import React, { Component } from "react";
import { View, Text, FlatList, ActivityIndicator,Image } from "react-native";
import { List, ListItem, SearchBar } from "react-native-elements";
import CardComponent from './CardComponent';
function getCardComponentArray() {
var texts = ['1', '2', '3', '4', '5'];
var cardComponents = texts.map((text) => <CardComponent title={text} />);
return cardComponents;
}
function getData() {
var texts = ['1', '2', '3', '4', '5'];
return texts
}
class CardFlatList extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false
};
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
this.setState({
data: getData(),
error: null,
loading: false,
refreshing: false
});
};
handleRefresh = () => {
this.setState(
{
page: 1,
seed: this.state.seed + 1,
refreshing: true
},
() => {
this.makeRemoteRequest();
}
);
};
handleLoadMore = () => {
this.setState(
{
page: this.state.page + 1
},
() => {
this.makeRemoteRequest();
}
);
};
renderSeparator = () => {
return (
<View
style={{
height: 2,
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />;
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
}}
>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
// <List>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<CardComponent
eventname={'Halloween'}
eventveranstalter={'park'}
eventuhr={'17:00'}
eventort={'berlin'}
eventimage={'http://whatstonightapp.com/wp-content/uploads/2016/12/background_light-1.jpg'}
eventtag1={'party'}
eventtag2={'music'}
eventtag3={'dance'}
>
</CardComponent>
)}
keyExtractor={item => item.email}
ItemSeparatorComponent={this.renderSeparator}
// ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
onRefresh={this.handleRefresh}
refreshing={this.state.refreshing}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={50}
/>
// </List>
);
}
}
export default CardFlatList;
You can do it as following.
render() {
return (
// <List>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<CardComponent
navigation={this.props.navigation}
eventname={'Halloween'}
eventveranstalter={'park'}
eventuhr={'17:00'}
eventort={'berlin'}
eventimage={'http://whatstonightapp.com/wp-content/uploads/2016/12/background_light-1.jpg'}
eventtag1={'party'}
eventtag2={'music'}
eventtag3={'dance'}
>
</CardComponent>
)}