How to prevent extra renders with useLiveQuery? #1661
Replies: 2 comments 1 reply
-
Like this? export const MyComponent = () => {
const loaded = useRef(false);
const dbData = useLiveQuery(async () => {
const r = await db.myTable.toArray();
loaded.current = true;
return r;
});
const data = loaded.current ? dbData : fallbackData;
// Render something with the data...
return <div>{data}</div>;
}; |
Beta Was this translation helpful? Give feedback.
-
useLiveQuery is composed as: (querier, deps, def) => useObservable(
() => liveQuery(querier),
deps,
def
) As you see, the useObservable() takes a function that creates an observable. It is possible to chain the observable returned from liveQuery() with a filtering functionality and do something like this: useObservable(
() => createFilteredObservable(liveQuery(querier), data => data?.length > 25)
) Rxjs could be used for these kind of requirements and has already a filter operator. import { liveQuery } from 'dexie';
import { useObservable } from 'dexie-react-hooks';
import { from, filter } from 'rxjs';
export function useFilteredLiveQuery(querier) {
return useObservable(
() => from(liveQuery(querier))
.pipe(
filter(dbData => dbData?.length >= 50)
)
);
} This would be a way to prevent noop re-renders. That said, I am also looking in to allow throttling configuration for live queries - but that use case is more about preventing too frequent querying (and rendering) in cases of extremely frequent write transactions. |
Beta Was this translation helpful? Give feedback.
-
Let's say that I have some initial data that I want to render while entries are added to my DB. To be precise, let's say that I have 4 network requests that each add 25 items to the DB, and I want to start rendering the data from the DB once 50 items are loaded. I can do this:
Beta Was this translation helpful? Give feedback.
All reactions