Search code examples
react-nativesqliterxdb

WebSQL threw an error [Error: Error code 1: no such table: document-store]


We are using react-naive-sqlite-2 in our application with RxDB and started getting this error somewhat sporadically. It seems to happen after we remove the database. I was surprised to see this was a WebSQL error since we are using react-native and WebSQL is deprecated. I don't have great ways to debug this but my hunch is that we have some code that still tries to access the now dead database.

This is the code we use to set up our database:

import SQLiteAdapterFactory from 'pouchdb-adapter-react-native-sqlite'
import SQLite from 'react-native-sqlite-2'
import { addRxPlugin, createRxDatabase } from 'rxdb'
import { RxDBReplicationGraphQLPlugin } from 'rxdb/plugins/replication-graphql'

import type { DatabaseType } from '../generated'

/**
 * SQLITE SETUP
 */
const SQLiteAdapter = SQLiteAdapterFactory(SQLite)
addRxPlugin(SQLiteAdapter)
addRxPlugin(require('pouchdb-adapter-http'))

/**
 * Other plugins
 */
addRxPlugin(RxDBReplicationGraphQLPlugin)

export const getRxDB = async () => {
  return await createRxDatabase<DatabaseType>({
    name: 'gatherdatabase',
    adapter: 'react-native-sqlite', // the name of your adapter
    multiInstance: false,
  })

The issue happens after we logout and attempt to log back in. When we logout, we call removeRxDatabase. Has anyone ran into this kind of issue before or know of ways to debug?


Solution

  • For posterity, the issue was that we had a reference to the database in our state management library (Zustand) that was being held onto past logout. When we tried to login again, our getOrCreateDatabase function didn't make a new one but it wasn't valid since we had run database.remove() in rxdb. We ended up just clearing the Zustand db and calling database.remove() at one place.

    export const useRxDB = create<UseRxDBType>((set, get) => ({
      database: undefined,
      /**
       * we set the database to ready in the LocalDocument store once local docs are loaded into the store
       */
      databaseIsReady: false,
      getOrCreateDatabase: async () => {
        let database = get().database
    
        if (!database) {
          database = await createRxDatabase()
    
          if (!Rx.isRxDatabase(database)) throw new Error(`database isnt a valid RxDB database.`)
    
          set({ database })
        }
    
        return database
      },
      resetDatabase: async () => {
        const database = get().database
    
        if (database) {
          await database.remove()
          set({ database: undefined })
        }
      },
    }))