SQLite Forum

Problem with select from Sqlite Expo. I can't save the array returned by the query through the hook function
Login

Problem with select from Sqlite Expo. I can't save the array returned by the query through the hook function

(1.1) Originally by Morais (001533) with edits by Richard Hipp (drh) on 2020-06-03 22:12:09 from 1.0 [source]

import React, {useState} from 'react';
import {DatabaseConnection} from '../database/conex';
import {DatabaseInit} from '../database/dbinit';
import { FlatList, Text, View } from 'react-native';

var db = null;

export default function viewAllUser(){

    db = DatabaseConnection.getConnection();
    const [users, setUsers] = useState([]);

    db.transaction(tx => {
        tx.executeSql('SELECT * FROM user', [], (tx, results) => {
          var temp = [];
          for (let i = 0; i < results.rows.length; ++i) {
            temp.push(results.rows.item(i));                               
          }             
          {() => setUsers(temp)}
        });  

      });
     console.log(users);
}

(2) By Larry Brasfield (LarryBrasfield) on 2020-06-04 00:58:18 in reply to 1.1 [link] [source]

I answer this because it probably cannot be answered as written. I am guessing at the problem because there is too little data to permit something more reasoned.

1st problem: There is no apparent association in above code between the 'db' object and any named SQLite database file. As far as the code reads, the connection could be on an empty, in-memory database.

2nd problem: There is no reason, apparent within the above post, to believe the query operation was completed without error. So there may well have been no temp.push(...) calls and the () => setUsers(temp) may have never executed.

3rd problem: There is too little information here to support a guess as to what result was expected. I surmise that the console.log(users); was supposed to produce output somewhere which was not seen when examined.

4th problem: There is nothing beyond the thread title to suggest what output(s) were actually observed.

5th problem: There is nothing in the way of things that have been tried, observations made, or reasons to believe the problem lies in the code shown.

If I was not too lazy to find it just now, I would link to an article about how to formulate an effective request for help on internet fora. The above post is a good example of how not to formulate one. (Sorry if that's harsh, but it has to be said.)

(3) By example-user on 2020-06-08 19:37:53 in reply to 1.1 [link] [source]

// I think the issue is:
{() => setUsers(temp)}
// This creates a function that you are not calling, so `setUsers` is never executed
() => 
// Replace with:
setUsers(temp)