MoneyDB.js 4.27 KB
Newer Older
Soo Hyun Kim's avatar
Soo Hyun Kim committed
1
2
3
import { DEBUG, enablePromise, openDatabase } from 'react-native-sqlite-storage';
import { SafeAreaView, StyleSheet, Text, View, TextInput, FlatList, Button } from 'react-native';
import React, { useEffect, useState } from 'react';
Choi Ga Young's avatar
Choi Ga Young committed
4

Soo Hyun Kim's avatar
Soo Hyun Kim committed
5
6
DEBUG(true);
enablePromise(true);
Choi Ga Young's avatar
Choi Ga Young committed
7

Soo Hyun Kim's avatar
Soo Hyun Kim committed
8
9
10
11
12
const db = openDatabase({
  name: 'MyMoney',
  location: 'default',
  createFromLocation: '~MyMoney.db', // android/src/main/assets/TestDB.db 파일을 위치 시킴
});
Choi Ga Young's avatar
Choi Ga Young committed
13
14

function MoneyDB() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
15
16
17
  const [money, setMoney] = useState([]);
  const [expense, setExpense] = useState(0)
  const [income, setIncome] = useState(0)
Choi Ga Young's avatar
Choi Ga Young committed
18
19
20

  console.log('money db')

Soo Hyun Kim's avatar
Soo Hyun Kim committed
21
22
  const populateDatabase = async DB => {
    await DB.transaction(queryMoney); // 반드시 (await db)를 해야 프라미스가 성공
Choi Ga Young's avatar
Choi Ga Young committed
23
24
  };

Soo Hyun Kim's avatar
Soo Hyun Kim committed
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
  const loadAndQueryDB = async () => {
    try {
      console.log('load and db query ....');
      await populateDatabase(await db);
    } catch (error) {
      console.log(error);
    }
  };

  const closeDatabase = async DB => {
    if (DB) {
      console.log('closing database ...');
      try {
        (await DB).close(
          () => {
            console.log('Database was closed successfully');
          },
          err => console.log(err),
        );
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log('Database was not opened');
    }
  };

  const queryMoney = async tx => {
    console.log('Excuting user query');
    try {
      const [txn, results] = await tx.executeSql('SELECT * FROM Money');
      console.log('item length', results.rows.length);
      const temp = [];
      for (let i = 0; i < results.rows.length; i++) {
        const element = results.rows.item(i);
        temp.push(element);
        console.log('item ', element);
      }
      setMoney(temp);
    } catch (error) {
      console.log('error in query money', error);
    }
  };

  const insertData = async () => {
    try {
      (await db).transaction((tx) => {
        console.log("데이터 삽입하기");
        tx.executeSql('INSERT INTO Money (expense, income) VALUES (?,?);',
          [expense, income],
          () => { console.log("삽입 성공"); },
          (error) => console.log(error))
      })
    } catch (error) {
      console.log('error in insert data', error)
    }
  }

  //수정 전 코드
  // const insertData = async () => {
  //   await db.transaction(async (tx) => {
  //     console.log("데이터 삽입하기");
  //     tx.executeSql('INSERT INTO Money (expense, income) VALUES (?,?);',
  //       [expense, income],
  //       () => { console.log("삽입 성공"); },
  //       (error) => console.log(error))
  //   })
  // }

Choi Ga Young's avatar
Choi Ga Young committed
94
  useEffect(() => {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
95
96
97
98
99
    loadAndQueryDB();
    return () => {
      // closeDatabase(await db); // 컴포넌트 없어질 때 디비 닫기 Error!!!
    };
  }, []);
Choi Ga Young's avatar
Choi Ga Young committed
100

Soo Hyun Kim's avatar
Soo Hyun Kim committed
101
102
103
104
105
  let listViewItemSeparator = () => {
    return (
      <View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
    );
  };
Choi Ga Young's avatar
Choi Ga Young committed
106

Soo Hyun Kim's avatar
Soo Hyun Kim committed
107
108
109
110
111
112
113
114
115
116
117
  let listItemView = item => {
    console.log('item in list view', item);
    return (
      <View>
        <Text>Expense: {item.expense} Age: {item.income}</Text>
      </View>
    );
  };

  console.log('money', money);
  console.log(expense, income)
Choi Ga Young's avatar
Choi Ga Young committed
118
  return (
Soo Hyun Kim's avatar
Soo Hyun Kim committed
119
120
    <SafeAreaView>
      <Text>db test</Text>
Choi Ga Young's avatar
Choi Ga Young committed
121
      <View>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
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
        <Text style={style.Font}>-데이터 입력 테스트</Text>
        <Text>expense</Text>
        <TextInput
          placeholder="expense"
          onChangeText={
            (expense) => setExpense(expense)
          }
        />
        <Text>income</Text>
        <TextInput
          placeholder="income"
          onChangeText={
            (income) => setIncome(income)
          }
        />
        <Button title='데이터 삽입하기' onPress={insertData} />
      </View>
      <View style={{ backgroundColor: 'gray' }}>
        <Text style={style.Font}>-데이터</Text>
        <View>
          <FlatList
            data={money}
            ItemSeparatorComponent={listViewItemSeparator}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item }) => listItemView(item)}
          />
        </View>
        <Button title='데이터 다시 불러오기' onPress={loadAndQueryDB} />
Choi Ga Young's avatar
Choi Ga Young committed
150
      </View>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
151
152
    </SafeAreaView>
  );
Choi Ga Young's avatar
Choi Ga Young committed
153
154
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
155
156
157
158
159
const style = StyleSheet.create({
  Font: {
    fontSize: 24
  }
});
Choi Ga Young's avatar
Choi Ga Young committed
160
161

export default MoneyDB