I'm new in sqlite and react native. (my app is with expo sqlite and expo react native) I'm trying to save data from an API to a table in SQLite database. The table name is "tb_user"
// MY DB
tx.executeSql(
"CREATE TABLE IF NOT EXISTS tb_user (ID_user INTEGER PRIMARY KEY, username TEXT, senha TEXT, ID_empresa INT, nome_empresa TEXT, status INT);"
);
// INSERT TO DB
const create = (obj) => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
//comando SQL modificável
tx.executeSql(
"INSERT INTO tb_user (ID_user, username, senha, ID_empresa, nome_empresa, status) values (?, ?, ?, ?, ?, ?);",
[obj.ID_user, obj.username, obj.senha, obj.ID_empresa, obj.nome_empresa, obj.status],
//-----------------------
(_, { rowsAffected, insertId }) => {
if (rowsAffected > 0) resolve(insertId); // resultado da operação
else reject("Error inserting obj: " + JSON.stringify(obj)); // insert falhou
},
(_, error) => reject(error) // erro interno em tx.executeSql
);
});
});
};
//MY CODE IN SCREEN
const importTbUser = () => {
fetch('url_API')
.then( (res) => res.json())
.then( ( res ) => {
this.setState ({
data: res.data || []
})
.then(
data.map((user) => {
Tb_user.create( {ID_user:user.ID_user, username:user.username, senha:user.senha, ID_empresa:user.ID_empresa, nome_empresa:user.nome_empresa, status:user.status_user} )
})
)
})
.catch( ( error ) => console.error(error) )
Obviously this code doesn't work, how can i make it work?
My application has a button with "onPress={import bUser}", so, when clicking on the button, it inserts the data that is in the API into the database. I saw some videos, but they only show how to consume an API, without inserting it into a database.