reactjsnestdexie

How to track if dexie UseLiveQuery is finished


I want to display a loader while a UseLiveQuery is not finished and display a "not found component" if the UseLiveQuery has returned an empty array.

Is there a simple way to do that?

Thank you very much.


Solution

  • It's easiest when your querier returns an array (see below). Then a result of undefined means still loading, while an empty array means finished loading but with zero results.

    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>;
    

    But if your querier returns the result from table.get(), a value of undefined could both mean that query is still loading or that the requested id was not found. To distinguish between the two, you could let the querier return something that makes it easier to distinguish between the two. For example, let the querier return the result as an item in an array and supply a third argument to useLiveQuery() with an empty array (something else than undefined) as a default result.

    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.
    

    That said, you'll normally not need a spinner when querying indexedDB (unless for very complex queries). In this case, probably better to just return null instead of <Spinner />, to bother the end-user the least.