'React native function return nothing
I'm trying to do something simple here - connect to a sqlite database and return the number of records. In the code below I can output the len variable with console.log, but nothing gets returned. Am I missing something obvious? Thanks.
const db = SQLite.openDatabase({ name: 'favorites.db' });
export default class PlayerScreen extends React.Component {
fetch(){
console.log('fetching data from database');
var query = "SELECT * FROM items";
var params = [];
db.transaction((tx) => {
tx.executeSql(query,params, (tx, results) => {
var len = results.rows.length;
return len;
}, function(){
console.log('Profile: Something went wrong');
});
});
}
render() {
return <Text>{this.fetch()}</Text>
}
}
Solution 1:[1]
A lot of things are wrong here. Fetch is an asynchronous concept and React rendering is synchronous. You cannot use fetch or anything asynchronously inside the render method.
So, what should you do instead?
First, do the fetch in the componentDidMount of the component. Also set an initial state in componentWillMount
componentWillMount() {
this.state = { length: 0 };
}
componentDidMount() {
// I use call here to make sure this.fetch gets the this context
this.fetch.call(this);
}
Secondly, attach the results to the innerState of the component in your fetch method
fetch() {
var query = "SELECT * FROM items";
var params = [];
db.transaction((tx) => {
tx.executeSql(query,params, (tx, results) => {
var len = results.rows.length;
// this.setState will trigger a re-render of the component
this.setState({ length: len });
}, function(){
console.log('Profile: Something went wrong');
});
});
}
Now, in the render method, you can use this.state.length to render the value.
render() {
return <Text>{this.state.length}</Text>
}
Hope this helps you out
Solution 2:[2]
Just putting this here for any other poor souls who this may help since this thread was the top result for me:
SQL isn't case sensitive, but React is. All my variables were lowercase, but my SQL tables used uppercase. So "SELECT key" actually returned "Key".
Therefore, rewriting the SQL query as "SELECT key as key" fixed it for me, since the first "key" isn't case sensitive, but the second one is.
Alternatively, just change the database headers to whatever case you'll be using in your program.
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 | dejakob |
Solution 2 | MacKenzie |