2

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'],
    },
};

1 Answer 1

1

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")
        })
    )
    })
  }, []);
}
Sign up to request clarification or add additional context in comments.

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.