'need to return data from db transaction react native
i beginner in react native in main component i call database to execute my command and then i need to return data for me but after run console log me undefined can help me to solve this problem.thanks
my main component:
const requestJob = async () => {
let queryselect = 'SELECT * FROM tbl_messages ';
var Result = await Select(queryselect);
if (Result == false) {
console.log('no data')
} else {
console.log(Result);
}
}
in my database component
var db = openDatabase({ name: 'message.db', createFromLocation: 1 });
db.transaction(tx => {
tx.executeSql(
query,
[],
(tx, results) => {
var len = results.rows.length;
if (len == 0) {
console.log('no ');
return false;
} else {
var temp = [];
for (let i = 0; i < results.rows.length; ++i) {
temp.push(results.rows.item(i));
}
return temp;
}
}
);
});
}
Solution 1:[1]
use Promise
export const get = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
query,
[],
(tx, results) => {
var len = results.rows.length;
if (len == 0) {
console.log('no ');
return false;
} else {
var temp = [];
for (let i = 0; i < results.rows.length; ++i) {
temp.push(results.rows.item(i));
}
return temp;
}
}
);
});
});
};
and read:
const [results, setResults] = useState([]);
const Read = async () => {
const results = await get();
console.log(results)
setResult(results);
}
useEffect(() => {
read();
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sergioriverafl |