-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
108 lines (93 loc) · 2.25 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
import React, { Component } 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 Component {
state = {
songs: [],
offset: 0,
query: "Drake",
isFetching: false,
isEmpty: false,
token: null,
isTokenFetching: false
};
async loadNextPage() {
const { songs, offset, query, token, isFetching, isEmpty } = this.state;
if (isFetching || isEmpty) 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({ isEmpty: true });
}
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(
{
isEmpty: false,
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}>
<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
}
});