I posted a previous post and couldn't send the code, so this page reported an error so I resubmitted it
When it's running, I enter user and password and press the login button, I get an error: ERROR Cannot convert null value to object
//App.js
import React, { useState } from 'react';
import { StyleSheet, View, TextInput, Button, FlatList, Text } from 'react-native';
import SQLite from 'react-native-sqlite-storage';
//import axios from 'axios';
const App = () => {
// Kh?i t?o state s? luu tr? thông tin ngu?i dùng
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [sqliteData, setSqliteData] = useState([]); // Thêm 'sqliteData' vào danh sách các state
// Hàm x? lý khi ngu?i dùng nh?n nút Login
const handleLogin = async () => {
//alert('login');
//console.log('login1');
try {
// K?t n?i b?ng co s? d? li?u
const db = SQLite.openDatabase(
{
name: 'Cafe.db',
location: 'default',
//createFromLocation: '~www/test.db',
},
() => {
console.log('Connected to the database.');
},
(error) => {
console.error('Failed to connect to the database.', error);
}
);
// Th?c hi?n truy v?n SQL s? lây d? li?u t? b?ng
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM TABUSERNAME',
[],
(_, result) => {
if (result.rows) {
const rows = result.rows.raw();
setSqliteData(rows); // Luu tr? d? li?u t? SQLite vào state 'sqliteData'
} else {
console.log('No rows returned from the query.');
}
},
error => {
console.error('Failed to execute query.', error);
}
);
});
// Ðóng k?t n?i co s? d? li?u khi không s? d?ng n?a
//return () => {
db.close();
console.log('Database connection closed.');
//};
} catch (error) {
console.error(error.message);
}
};
// Hàm x? lý khi ngu?i dùng nh?n nút Signup
const handleSignup = async () => {
try {
//
} catch (error) {
console.error(error.message);
}
};
return (
<View style={styles.container}>
<View style={styles.flatlist}>
{/* Hi?n th? d? li?u trong ô lu?i */}
<FlatList
data={sqliteData}
renderItem={({ item }) => <Text>{JSON.stringify(item)}</Text>}
keyExtractor={(_, index) => index.toString()}
/>
</View>
<View style={styles.inputText}>
<View style={styles.text}>
<View style={styles.user}>
{/* ngu?i dùng nh?p tên ngu?i dùng */}
<TextInput placeholder="Username" onChangeText={setUsername} />
</View>
<View style={styles.pass}>
{/* ngu?i dùng nh?p m?t kh?u */}
<TextInput placeholder="Password" onChangeText={setPassword} secureTextEntry={true} />
</View>
</View>
<View style={styles.button}>
<View style={styles.login}>
{/* Nút s? th?c hi?n ch?c nang dang nh?p */}
<Button title="Login" onPress={handleLogin} />
</View>
<View style={styles.signup}>
{/* Nút s? th?c hi?n ch?c nang dang ký */}
<Button title="Signup" onPress={handleSignup} />
</View>
</View>
</View>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex : 1,
backgroundColor : '#e7feff',
},
flatlist: {
//top : 340,
//width : 50,
//height : 50,
backgroundColor : 'red',
},
inputText : {
top: 340,
},
text : {
marginLeft : 30,
},
button : {
width : 360,
height : 150,
marginHorizontal : 20,
justifyContent : 'center',
},
login : {
},
signup : {
top : 20,
},
})
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const app = express();
const port = 3000;
app.use(bodyParser.json());
const config = {
user: 'sa',
password: '123456',
server: 'MICROSOFT',
database: 'Cafe',
options: {
encrypt: false // N?u không s? d?ng k?t n?i b?o m?t, d?t encrypt là false
}
};
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
await sql.connect(dbConfig);
const query = `SELECT * FROM TABUSERNAME WHERE USERNAME = @username AND PASSWORDS = @password`;
const request = new sql.Request();
request.input('username', sql.VarChar, username);
request.input('password', sql.VarChar, password);
const result = await request.query(query);
if (result.recordset.length > 0) {
res.json({ success: true, message: 'Login successful' });
} else {
res.status(401).json({ success: false, message: 'Login failed' });
}
} catch (err) {
console.error('Database connection error', err);
res.status(500).json({ success: false, message: 'Internal server error' });
} finally {
sql.close();
}
});
/*
app.post('/login', async (req, res) => {
try {
await sql.connect(config);
const result = await sql.query(`SELECT * FROM TABUSERNAME WHERE USERNAME='${req.body.username}' AND PASSWORDS='${req.body.password}'`);
sql.close();
res.json(result.recordset);
} catch (error) {
res.status(500).send(error.message);
}
});
*/
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});