I tried to fetch data from an embedded sqlite db and displayed it in list format. The fetchData() function is working, with correct returned result. However, when I used setState() to update the state, react did not re-render. Next I tried to setState() with array [‘a’,’b’,’c’] at componentDidMount(). React did re-render and showed a, b, c.
JavaScript
x
49
49
1
import React from 'react';
2
import sqlite3 from 'sqlite3';
3
4
5
type MyProps = { };
6
type MyState = { data: Array<string> };
7
8
class App extends React.Component<MyProps, MyState>{
9
constructor(props) {
10
super(props);
11
this.state = { data: [] };
12
13
}
14
15
async fetchData(){
16
var db = new sqlite3.Database({$DB_PATH});
17
var res: string[] = [];
18
await db.each('select * from table', [], (err, row) => { //selecting 10 rows from table
19
if (err) {
20
throw err;
21
}
22
res.push(row.name);
23
});
24
db.close();
25
console.log(this.state.data) //array length = 0
26
this.setState({data: res})
27
console.log(this.state.data) //array length = 10
28
}
29
30
async componentDidMount() {
31
await this.fetchData();
32
}
33
34
render() {
35
return (
36
<div>
37
<ul>
38
{this.state.data.map(el => (
39
<li>
40
{el}
41
</li>
42
))}
43
</ul>
44
</div>
45
);
46
}
47
}
48
export default App;
49
Advertisement
Answer
Because of db.each
won’t return a Promise
so that you cannot reach result by ‘await’ statement.
Refer to the APIs, you’ll need to this:
JavaScript
1
2
1
each(sql: string, params: any, callback?: (this: Statement, err: Error | null, row: any) => void, complete?: (err: Error | null, count: number) => void): this;
2
so, you should access the result in the complete
callback, code like so:
JavaScript
1
16
16
1
async fetchData() {
2
const db = new sqlite3.Database({ $DB_PATH });
3
const res: string[] = [];
4
await db.each('select * from table', [], (err, row) => { // selecting 10 rows from table
5
if (err) {
6
throw err;
7
}
8
res.push(row.name);
9
}, () => {
10
console.log(this.state.data) // array length = 0
11
this.setState({ data: res })
12
console.log(this.state.data) // array length = 10
13
db.close();
14
});
15
}
16
Hope it will be helpful.
Besides, you can also have a try with Statement#all([param, ...], [callback])
function which is a better than each
.