6

I am using this library: https://github.com/andpor/react-native-sqlite-storage for my react native project.

I retrieve single row from database like this:

db.transaction((tx) => {
        tx.executeSql('SELECT * FROM user where id = 1', [], (tx, results) => {
            console.log("Query completed");

            var len = results.rows.length;
           if (len > 0) {
                let row = results.rows.item(0);
                this.setState({userName: row.name});
            }
        });
    });


return (
        <View>
            <Text>{this.state.userName}</Text>
        </View>
    )

But now i want to fetch all data from database, tell me what wrong i am doing in below code:

 db.transaction((tx) => {
        tx.executeSql('SELECT * FROM user', [], (tx, results) => {
            console.log("Query completed");

            var len = results.rows.length;
           for (let i = 0; i < len; i++) {
                let row = results.rows.item(i);
                this.setState({record: row.name});
            }
        });
    });




return (
            <View>
                <FlatList data={this.state.record}
                          keyExtractor={(x,i) => 1}
                          renderItem={ ({item}) =>
                              <ListItem><Text>{item.name}</Text></ListItem>
                          }
                />
            </View>
        )

can anyone guide me how can i show database data in listview.

2 Answers 2

1

Your state value for FlatList data should be an array and you are setting it to a single string every time you itterate through.

Try changing it like below

this.setState((prevState) => ({ record : prevState.record.push(row.name)}))

PS: you need to set your initial state value for record as an empty array or so.

Sign up to request clarification or add additional context in comments.

5 Comments

what is prevState?
Kindly elaborate a bit
More info can be found in react's component docs
Any working example for react native sqlite data retrieval in list ?
bennygenel - can u help me please with sqlite ? i have the insert fetch and delete functions but for some unclear reason it doesn't work .
0

It works like this

record = this.state.record.slice()
                record.push(row.name)
                this.setState({ record: record })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.