-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
130 lines (121 loc) · 2.85 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
123
124
125
126
127
128
129
130
import { StatusBar } from 'expo-status-bar';
import { Button, StyleSheet, Text, View } from 'react-native';
import * as SQLite from 'expo-sqlite';
import { useEffect, useState } from 'react';
const datapoints = (db) => {
return new Promise((resolve, reject) => {
db.exec([
{
sql: `SELECT at FROM hello_worlds`,
args: []
}
], false, (err, result) => {
if (err) {
reject(err)
return
}
const rows = result[0].rows
const times = rows.map((row) => {
return row.at
})
resolve(times)
})
})
}
const updateLocal = (db, at) => {
return new Promise((resolve, reject) => {
db.exec([
{
sql: `INSERT INTO hello_worlds (at) VALUES (?)`,
args: [
at.getTime()
]
}
], false, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
const updateRemote = async (db) => {
const dp = await datapoints(db)
const body = JSON.stringify({ats: dp})
const response = await fetch('https://mtba-svc.fly.dev/api/datapoints', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: body
})
return response.json()
}
export default function App() {
const [db, setDB] = useState(null)
const [status, setStatus] = useState('')
const onPressInsert = () => {
if (!db) {
return
}
const now = new Date()
const run = async () => {
await updateLocal(db, now)
setStatus(`logged local entry at=${now}, now syncing to remote`)
await updateRemote(db)
setStatus(`logged and synced entry at=${now}`)
}
run().then(() => {}, (err) => {
setStatus(`error=${err}`)
})
}
useEffect(() => {
let run = async () => {
const db = SQLite.openDatabase('greetings.db')
const create = await new Promise((resolve, reject) => {
db.exec([
{
sql: `
CREATE TABLE IF NOT EXISTS hello_worlds (
at NUMERIC PRIMARY KEY ASC ON CONFLICT REPLACE
)`,
args: []
}
], false, (err, result) => {
if (err) {
return reject(`while creating table: ${err}`)
}
resolve(result)
})
})
setDB(db)
return "ready to log"
}
run().then((status)=> {
setStatus(status)
}, (err) => {
setStatus(`err=${err}`)
})
}, [])
return (
<View style={styles.container}>
<Text>status={status}</Text>
<Button
onPress={onPressInsert}
title="Insert"
color="#841584"
accessibilityLabel="Insert item into database"
/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});