· 7 years ago · Jan 14, 2019, 05:02 AM
1import React from 'react';
2import {StyleSheet, Text, TextInput, View, Button, FlatList, Alert} from 'react-native';
3import Expo, { SQLite } from 'expo';
4
5const db = SQLite.openDatabase('coursedb.db');
6
7export default class App extends React.Component {
8 constructor(props) {
9 super(props);
10 this.state = {credit: '', title: '', courses: []};
11 }
12
13 componentDidMount() {
14 // Create course table
15 db.transaction(tx => {
16 tx.executeSql('create table if not exists course (id integer primary key not null, credits int, title text);');
17 });
18 this.updateList();
19 }
20
21 // Save course
22 saveItem = () => {
23 db.transaction(tx => {
24 tx.executeSql('insert into course (credits, title) values (?, ?)', [parseInt(this.state.credit), this.state.title]);
25 }, null, this.updateList)
26 }
27
28 // Update courselist
29 updateList = () => {
30 db.transaction(tx => {
31 tx.executeSql('select * from course', [], (_, { rows }) =>
32 this.setState({courses: rows._array})
33 );
34 });
35 }
36
37 // Delete course
38 deleteItem = (id) => {
39 db.transaction(
40 tx => {
41 tx.executeSql(`delete from course where id = ?;`, [id]);
42 }, null, this.updateList
43 )
44 }
45
46 listSeparator = () => {
47 return (
48 <View
49 style={{
50 height: 5,
51 width: "80%",
52 backgroundColor: "#fff",
53 marginLeft: "10%"
54 }}
55 />
56 );
57 };
58
59 render() {
60 return (
61 <View style={styles.container}>
62 <TextInput placeholder='Title' style={{marginTop: 30, fontSize: 18, width: 200, borderColor: 'gray', borderWidth: 1}}
63 onChangeText={(title) => this.setState({title})}
64 value={this.state.title}/>
65 <TextInput placeholder='Credits' keyboardType="numeric" style={{ marginTop: 5, marginBottom: 5, fontSize:18, width: 200, borderColor: 'gray', borderWidth: 1}}
66 onChangeText={(credit) => this.setState({credit})}
67 value={this.state.credit}/>
68 <Button onPress={this.saveItem} title="Save" />
69 <Text style={{marginTop: 30, fontSize: 20}}>Courses</Text>
70 <FlatList
71 style={{marginLeft : "5%"}}
72 keyExtractor={item => item.id}
73 renderItem={({item}) => <View style={styles.listcontainer}><Text style={{fontSize: 18}}>{item.title}, {item.credits} </Text>
74 <Text style={{fontSize: 18, color: '#0000ff'}} onPress={() => this.deleteItem(item.id)}>done</Text></View>} data={this.state.courses} ItemSeparatorComponent={this.listSeparator}
75 />
76 </View>
77 );
78 }
79
80}
81
82const styles = StyleSheet.create({
83 container: {
84 flex: 1,
85 backgroundColor: '#fff',
86 alignItems: 'center',
87 justifyContent: 'center'
88 },
89 listcontainer: {
90 flexDirection: 'row',
91 backgroundColor: '#fff',
92 alignItems: 'center'
93 }
94});