Skip to content

Instantly share code, notes, and snippets.

@bogoslavskiy
Last active October 16, 2019 13:32
Show Gist options
  • Save bogoslavskiy/2acb5a7ec62a3c5d969aeac3ea2d6e4b to your computer and use it in GitHub Desktop.
Save bogoslavskiy/2acb5a7ec62a3c5d969aeac3ea2d6e4b to your computer and use it in GitHub Desktop.
import React from 'react';
import { View, StyleSheet, ActivityIndicator } from 'react-native';
import { FlatList } from '../searchBarAnimation';
import { List, ListItem } from 'react-native-elements';
export default class Tab extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false
};
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const { page, seed } = this.state;
const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: page === 1 ? res.results : [...this.state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
});
})
.catch(error => {
this.setState({ error, loading: 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();
}
);
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View style={{paddingVertical: 20}}>
<ActivityIndicator animating size="large" />
</View>
);
};
renderHeader = () => {
if (!this.state.refreshing) return null;
return (
<View style={{marginTop: -40, paddingVertical: 20}}>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<FlatList
data={this.state.data}
renderItem={this._renderRow}
tabRoute={this.props.route.key}
renderItem={({item}) => (
<ListItem
roundAvatar
title={`${item.name.first} ${item.name.last}`}
subtitle={item.email}
avatar={{ uri: item.picture.thumbnail }}
containerStyle={{ borderBottomWidth: 0 }}
/>
)}
removeClippedSubviews={false}
ListFooterComponent={this.renderFooter}
ListHeaderComponent={this.renderHeader}
keyExtractor={item => item.login.uuid}
onRefresh={this.handleRefresh}
refreshing={this.state.refreshing}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={50}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment