-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRefreshableTopStoriesList.js
254 lines (245 loc) · 6.86 KB
/
RefreshableTopStoriesList.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import React,{ Component } from 'react'
import {
StyleSheet,
Text,
View,
ListView,
Image,
RefreshControl,
TouchableHighlight,
} from 'react-native'
import NewsItemWebView from './NewsItemWebView'
import SQLite from 'react-native-sqlite-storage'
SQLite.DEBUG(true)
SQLite.enablePromise(true)
SQLite.enablePromise(false)
const retreivenytimesurl = (section,format,apikey) => { return `https://api.nytimes.com/svc/topstories/v2/${section}.${format}?api-key=${apikey}`
}
const API_KEY = '<API_KEY>';
const default_thumbnail = 'http://d3biamo577v4eu.cloudfront.net/static/images/redesign/poster_default_thumb.gif'
const database_name = "Test.db"
const database_version = "1.0"
const database_displayname = "SQLite Test Database"
const database_size = 200000
var db
class RefreshableTopStoriesList extends Component{
constructor(props){
super(props)
this.state = {
loaded : false,
refreshing : false,
dataSource : new ListView.DataSource({
rowHasChanged : (row1,row2) => row1 !== row2,
}),
}
this.querySectionData = this.querySectionData.bind(this)
this.populateDb = this.populateDb.bind(this)
this.getNews = this.getNews.bind(this)
this._onRefresh = this._onRefresh.bind(this)
this.renderNewsItem = this.renderNewsItem.bind(this)
}
// this is for the initial render
componentDidMount(){
this.fetchData()
}
componentWillUnmount(){
//console.warn('unmounting')
}
loadingView(){
return (
<View style={styles.container}>
<Text>
{this.props.pageLoadingText}
</Text>
</View>
)
}
purgeSectionData(){
db.transaction((tx) => {
tx.executeSql('DELETE FROM NEWS_DATA where section = ? ',[this.props.section])
})
}
_onRefresh() {
this.setState({refreshing: true})
this.purgeSectionData()
this.fetchData()
this.setState({refreshing: false})
}
openCB(){
console.log("database opened")
}
errorCB(err) {
console.log("error: ",err);
return false;
}
successCB() {
console.log("SQL executed ...");
}
closeCB(){
console.log("closing db")
}
populateDatabase(db){
db.executeSql('SELECT 1 from Version LIMIT 1',[],
() => {
db.transaction(this.querySectionData,this.errorCB,() => {
console.log('completed transaction')
})
},
(error) => {
console.log("received version error:", error);
db.transaction(this.populateDb,this.errorCB,() => {
console.log('completed transaction')
db.transaction(this.querySectionData,this.errorCB,function(){
console.log('completed transaction')
this.closeDatabase()
})
})
})
}
populateDb(tx){
tx.executeSql('DROP TABLE IF EXISTS NEWS_DATA')
tx.executeSql('CREATE TABLE IF NOT EXISTS VERSION (version_id INTEGER PRIMARY KEY NOT NULL )',[],this.successCB,this.errorCB)
tx.executeSql('CREATE TABLE IF NOT EXISTS NEWS_DATA (section VARCHAR(32), json VARCHAR(65536))',[],this.successCB,this.errorCB)
this._fetchData(this.props.section).
then((response) => response.json()).
then((responseData) => {
db.transaction((tx) =>
tx.executeSql('INSERT INTO NEWS_DATA(section,json) values (?,?)',[this.props.section,JSON.stringify(responseData.results)])
)
}).
done()
}
querySectionData(tx){
tx.executeSql('SELECT json from NEWS_DATA where section = ?',[this.props.section],this.getNews,this.errorCB)
}
getNews(tx,results){
const row = results.rows.item(0);
if(!!row && !!row.json){
const news_json = JSON.parse(row.json)
this.setState({
loaded : true,
dataSource : this.state.dataSource.cloneWithRows(news_json),
})
}
else{
this._fetchData(this.props.section).
then((response) => response.json()).
then((responseData) => {
db.transaction((tx) => {
tx.executeSql('INSERT INTO NEWS_DATA(section,json) values (?,?)',[this.props.section,JSON.stringify(responseData.results)])
this.querySectionData(tx)
})
}).
done()
}
}
closeDatabase(){
const that = this
if(db){
db.close(that.closeCB,that,errorCB)
}
}
loadAndQueryDB(){
db = SQLite.openDatabase(database_name,database_version,database_displayname,database_size,this.openCB,this.errorCB)
this.populateDatabase(db)
}
async _fetchData(section){
const data = await fetch(retreivenytimesurl(section,this.props.format,API_KEY))
return data
}
fetchData(section=this.props.section){
this.setState({
loaded : false
})
this.loadAndQueryDB()
}
_renderSeparator(sectionID,rowID){
return (
<View
key={`${sectionID}-${rowID}`}
style={styles.separator}
/>
)
}
render(){
if(!this.state.loaded){
return this.loadingView()
}
return (
<ListView
refreshControl = {
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh}
/>
}
dataSource={this.state.dataSource}
renderRow = {this.renderNewsItem}
style = {styles.listView}
renderSeparator={(sectionID,rowID) => this._renderSeparator(sectionID,rowID)}
/>
)
}
renderNewsItem(newsitem){
const imgsrc = newsitem.multimedia[0] ? newsitem.multimedia[0].url : default_thumbnail
const url = newsitem.url
const title = newsitem.title
return (
<TouchableHighlight
onPress = {() => {return this.handleNewsItemClick(url,title)}}
underlayColor = {'grey'}
activeOpacity = {0.25}
>
<View style={styles.container}>
<Image source={{uri:imgsrc}} style={styles.thumbnail} />
<View style={styles.rightContainer}>
<Text style={styles.title} numberOfLines={3}>{newsitem.title}</Text>
</View>
</View>
</TouchableHighlight>
)
}
handleNewsItemClick(url,title){
this.props.navigator.push({
id : this.props.pageId,
component : NewsItemWebView,
name : title,
passProps: {url:url,title:this.props.title},
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
flexDirection : 'row',
alignItems: 'center',
paddingLeft : 15,
paddingRight : 15,
paddingTop : 5,
paddingBottom : 5,
},
rightContainer : {
flex : 1,
justifyContent : 'flex-start'
},
title:{
fontSize : 16,
textAlign : 'left',
marginLeft : 10,
},
year :{
textAlign : 'center'
},
thumbnail: {
width : 60,
height : 60,
},
separator: {
height: 1,
backgroundColor: '#CCCCCC',
marginLeft : 15,
marginRight : 15,
},
})
export default RefreshableTopStoriesList