expo-starter / expo-local-first-template

📱 A template for your local-first Expo project: Bun, Expo 51, TypeScript, TailwindCSS, DrizzleORM, Sqlite, EAS, GitHub Actions, Env Vars, expo-router, react-hook-form.
https://expostarter.com
MIT License
252 stars 18 forks source link

useLiveQuery does not accept a nullish database #17

Closed Kesmek closed 4 months ago

Kesmek commented 4 months ago

In the src/index.tsx file, you have a useLiveQuery being used in conjuction with a database from the useDatabase hook:

//...
  const {db} = useDatabase();
  const {data: habits, error} = useLiveQuery(db?.select().from(habitTable));
//...

However the useLiveQuery hook doesn't accept a nullish database query, and gives the following error:

Argument of type 'SQLiteSelectBase<"habits", "sync", SQLiteRunResult, { id: SQLiteColumn<{ name: "id"; tableName: "habits"; dataType: "string"; columnType: "SQLiteText"; data: string; driverParam: string; notNull: true; hasDefault: true; enumValues: [...]; baseColumn: never; }, object>; ... 5 more ...; createdAt: SQLiteColumn<...>; }...' is not assignable to parameter of type 'Pick<AnySQLiteSelect, "_" | "then"> | SQLiteRelationalQuery<"sync", unknown>'.
  Type 'undefined' is not assignable to type 'Pick<AnySQLiteSelect, "_" | "then"> | SQLiteRelationalQuery<"sync", unknown>'.

The only way to use useLiveQuery as far as I know (without this error) is by directly accessing the db from drizzle: import {db} from "@/db/drizzle". I understand that using hooks to access the database is better practice but I can't figure out how to resolve this issue with the hooks. Any help would be appreciated.

younes200 commented 4 months ago

hi @Kesmek,

The useDatabase hook works for both native SQLite (ExpoSqlite) and web (SQL.Js). However, the latter operates asynchronously due to the wasm preloader steps. As a solution, you can integrate a React component wrapper to verify the readiness of the database.

function ScreenPage() {
  const {db} = useDatabase();
  if(!db){
     return <Loader/>
  }
  return <ScreentContent db={db} />
  }

This step will be included in the ongoing code update.

Kesmek commented 4 months ago

Great, thanks for the suggested solution.