-
Notifications
You must be signed in to change notification settings - Fork 0
/
PicsScreen.js
79 lines (70 loc) · 1.77 KB
/
PicsScreen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import React from "react";
import { ActivityIndicator, FlatList, StyleSheet, View } from "react-native";
import Pic from "./Pic";
export default class PicsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
};
}
static navigationOptions = ({ navigation }) => {
const { params } = navigation.state;
return {
title: params ? params.routeName : null
};
};
componentDidMount() {
this.fetchPicsFromReddit();
}
async fetchPicsFromReddit() {
this.setState({
isLoading: true
});
let sorting = this.props.navigation.state.routeName.toLowerCase();
let url = "https://api.reddit.com/r/pics/" + sorting + ".json";
try {
let response = await fetch(url);
let responseJson = await response.json();
let pics = responseJson.data.children;
pics.map(pic => (pic.key = pic.data.id));
this.setState({
isLoading: false,
console: responseJson,
pics: pics
});
} catch (error) {
console.error(error);
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
// TODO improvement: add infinite scroll
return (
<View style={styles.container}>
<FlatList
data={this.state.pics}
refreshing={this.state.isLoading}
onRefresh={() => this.fetchPicsFromReddit()}
renderItem={({ item }) => (
<Pic navigation={this.props.navigation} item={item} />
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
});