drizzle-team / drizzle-team/drizzle-orm

[FEATURE]: Debounce useLiveQuery

Open
#2,953 3 comments 11 reactions 0 assignees View on GitHub
db/sqlite driver/expo-sqlite improvement
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

Thanks for the great ORM!

Today I used [patch-package](https://github.com/ds300/patch-package) to patch `drizzle-orm@0.33.0` for a React Native (Expo) app I'm working on.

I'm using `expo-sqlite` in combination with Drizzle's `useLiveQuery`. In the background entries are added in batches. This completely froze my application, because for every row inserted the state get's updated. So, I've added a debounce to fix this for me. I'm not sure if this is the way to go, but I would be more than happy to create a PR for this.

Here is the diff that solved my problem:

```diff
diff --git a/node_modules/drizzle-orm/expo-sqlite/query.js b/node_modules/drizzle-orm/expo-sqlite/query.js
index 6a41bbf..a8ba6b8 100644
--- a/node_modules/drizzle-orm/expo-sqlite/query.js
+++ b/node_modules/drizzle-orm/expo-sqlite/query.js
@@ -3,6 +3,19 @@ import { useEffect, useState } from "react";
import { is, SQL, Subquery } from "../index.js";
import { getTableConfig, getViewConfig, SQLiteTable, SQLiteView } from "../sqlite-core/index.js";
import { SQLiteRelationalQuery } from "../sqlite-core/query-builders/query.js";
+
+function debounce(func, wait) {
+ let timeout;
+ return function executedFunction(...args) {
+ const later = () => {
+ clearTimeout(timeout);
+ func(...args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
+}
+
const useLiveQuery = (query, deps = []) => {
const [data, setData] = useState(
is(query, SQLiteRelationalQuery) && query.mode === "first" ? void 0 : []
@@ -21,11 +34,16 @@ const useLiveQuery = (query, deps = []) => {
setUpdatedAt(/* @__PURE__ */ new Date());
};
query.then(handleData).catch(setError);
+ const debounceQuery = debounce(() => {
+ query.then(handleData).catch(setError);
+ }, 100);
+
if (is(entity, SQLiteTable) || is(entity, SQLiteView)) {
const config = is(entity, SQLiteTable) ? getTableConfig(entity) : getViewConfig(entity);
listener = addDatabaseChangeListener(({ tableName }) => {
if (config.name === tableName) {
- query.then(handleData).catch(setError);
+ debounceQuery();
}
});
}
```

This issue body was [partially generated by patch-package](https://github.com/ds300/patch-package/issues/296).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.