Home > database >  React Native Running on Expo - SQLite Error when using Pre-populated Database - TypeError: undefined
React Native Running on Expo - SQLite Error when using Pre-populated Database - TypeError: undefined

Time:04-05

I am using React Native on Expo with SQlite database, the goal is to create an offline Android App. The database is already prepopulated so I have copied it to assets/database/FarmersDB.db folder. I have gone through the official documentation and also suggestions provided here and other provided solutions but I end up with the error below.

TypeError: undefined is not a function (near '...db.transaction...')

My code is as follows:

//Login Component
import React, {useEffect, useState} from 'react'
import * as SQLite from 'expo-sqlite';
import * as FileSystem  from 'expo-file-system'
import {Asset } from 'expo-asset'

async function openDb() {
  if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory   "SQLite")).exists) {
    await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory   "SQLite");
  }
  await FileSystem.downloadAsync(
    Asset.fromModule(require("../assets/database/FarmerDB.db")).uri,
    FileSystem.documentDirectory   "SQLite/FarmerDB.db"
  );
  return SQLite.openDatabase("FarmerDB.db","1.0");
}

const LoginScreen = () => {
  useEffect(() => {
    
    const db = openDb()
    db.transaction((tx) =>{
      tx.executeSql(
        "SELECT * FROM Farmer WHERE id = 1",
        [],
        (tx,results) =>{
          console.log("success")
        }
      )
    })
  }, []);
}

The metro.config.js file in project root is as follows.

const { getDefaultConfig } = require('expo/metro-config');

const defaultConfig = getDefaultConfig(__dirname);

module.exports = {
    resolver: {
        assetExts: [...defaultConfig.resolver.assetExts,'db'],
    },
};

CodePudding user response:

After some struggle I got the solution,

const db = openDb() //This returns a promise 

So the code should look like below.

  const LoginScreen = () => {
  useEffect(() => {
   openDb()
    .then(db =>
    db.transaction((tx) =>{
      tx.executeSql(
        "SELECT * FROM Farmer WHERE id = 1",
        [],
        (tx,results) =>{
          console.log("success")
        })
    )
    })
  }, []);
}
  • Related