Skip to content

Support suspense in useSubscribe #19

@dpeek

Description

@dpeek

Because of the async nature of Replicache queries, useSubscribe currently has this type:

function useSubscribe<R>(rep:Replicache, query:(tx: ReadTransaction) => Promise<R>, def:R, deps:Array<any>):R {}

Where def allows users to provide a fallback value until the first query completes. In many cases there is no sensible value for users to provide here, meaning they fallback to null checking the results throughout their app:

function useDocument(rep:Replicache, id:string):Doc | null {
  return useSubscribe(cache, (tx) => {/*...*/}, null, []);
}

function SomeComponent({rep, id}:{rep:Replicache, id:string}) {
  let doc = useDocument(rep, id);
  if (!doc) return null;
  return <div>{doc.title}</div>
}

This can be avoiding by making useSubscribe support suspense. Basically the hook should throw a Promise that resolves once the first value is returned by the query.

Users can then wrap their useSubscribe components in a SuspenseBoundary that will suspend until all queries have returned a value, and no more null checks \o/

One thing to bear in mind while implementing is that suspending a component (aka throwing a promise in the render function) nukes all state for that component, so you need to maintain state outside of React.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions