-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
App.js
122 lines (103 loc) · 2.3 KB
/
App.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import React from 'react';
import {
StyleSheet,
Text,
View,
ActivityIndicator,
} from 'react-native';
import Search from './src/Components/Search';
import Listing from './src/Components/Listing';
import token from './src/api/token';
import search from './src/api/search';
const PAGE = 20;
export default class App extends React.Component {
constructor() {
super();
this.state = {
songs: [],
offset: 0,
query: 'Shpongle',
isFetching: false,
token: null,
isTokenFetching: false,
};
}
async loadNextPage() {
const { songs, offset, query, token, isFetching } = this.state;
if (isFetching) {
return;
}
this.setState({ isFetching: true });
const newSongs = await search({
offset: offset,
limit: PAGE,
q: query,
token,
});
if (newSongs.length === 0) {
console.log('no songs found. there may be an error');
}
this.setState({
isFetching: false,
songs: [...songs, ...newSongs],
offset: offset + PAGE,
});
}
async refreshToken() {
this.setState({
isTokenFetching: true,
});
const newToken = await token();
this.setState({
token: newToken,
isTokenFetching: false,
});
}
async componentDidMount() {
await this.refreshToken();
await this.loadNextPage();
}
handleSearchChange(text) {
// reset state
this.setState({
query: text,
offset: 0,
songs: [],
}, () => {
this.loadNextPage();
});
console.log('search text is', text);
}
async handleEndReached() {
await this.loadNextPage();
}
render() {
const { songs, query, isFetching } = this.state;
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Search
onChange={text => this.handleSearchChange(text)}
text={query}
/>
{
(isFetching && songs.length === 0)
? <ActivityIndicator />
: <Listing
items={songs}
onEndReached={() => this.handleEndReached()}
/>
}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'stretch',
justifyContent: 'flex-start',
margin: 10,
marginTop: 50,
},
});