reactjs - 如何跟踪 dexie UseLiveQuery 是否完成

标签 reactjs nest dexie

我想在 UseLiveQuery 未完成时显示加载程序,并在 UseLiveQuery 返回空数组时显示“未找到组件”。

有没有简单的方法可以做到这一点?

非常感谢。

最佳答案

当您的查询器返回一个数组时,这是最简单的(见下文)。那么未定义的结果意味着仍在加载,而空数组意味着已完成加载但结果为零。

const friends = useLiveQuery (() => db.friends.toArray());
if (!friends) return <Spinner />; // Still loading

return <ul>{
  friends.map(friend => <li key={friend.id}>
    {friend.name}, {friend.age}
  </li>)
}</ul>;

但是如果你的查询器返回 table.get() 的结果,未定义的值可能都意味着查询仍在加载或未找到请求的 ID。为了区分两者,您可以让查询器返回一些内容,以便更容易区分两者。例如,让查询器将结果作为数组中的一项返回,并向 useLiveQuery() 提供第三个参数。使用空数组(未定义的数组)作为默认结果。

const [friend, loaded] = useLiveQuery (
  () => db.friends.get(1).then(friend => [friend, true]),
  [], // deps...
  []  // default result: makes 'loaded' undefined while loading
);

if (!loaded) return <Spinner />; // Still loading...
if (!friend) return <NotFound ... />; // Loaded but friend not found

return <>{friend.name}, {friend.age}</>; // Loaded and friend found.

也就是说,在查询 indexedDB 时通常不需要微调器(除非非常复杂的查询)。在这种情况下,最好返回 null而不是<Spinner /> ,尽量不打扰最终用户。

关于reactjs - 如何跟踪 dexie UseLiveQuery 是否完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73526472/

相关文章:

javascript - IndexedDB-Dexie JS : Dynamically create stores

html - 从页面导航和返回页面时 CSS 更改 - React

attributes - 如何从引用选择器操作属性

c# - 自动映射时可以展平对象的一部分

javascript - 如何获取使用 dexie js 立即添加的值的 id?

javascript - 在 Dexie 数据库模式中指定不同的唯一键?

javascript - 我想通过单击 React js 中的按钮来选择输入框中的文本,但我的代码不起作用

reactjs - Material 用户界面|如何更改禁用的输入文本字段的字体颜色?

elasticsearch - 在Nest 2.x中合并BoolQueryDescriptor

elasticsearch - 在Nest Elasticsearch中使用术语汇总功能查找特定文档