Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useLiveQuery() #80

Merged
merged 18 commits into from
Feb 11, 2021
Merged

useLiveQuery() #80

merged 18 commits into from
Feb 11, 2021

Conversation

KATT
Copy link
Member

@KATT KATT commented Feb 11, 2021

  • React-only hook to watch a query using subscriptions
  • Constraint: that input & output on subscription() contains a prop called cursor

Example code

Server

// ...
import { OutputWithCursor } from '@trpc/react';

router
    .subscription('postsLive', {
      input: z.object({
        cursor: z.string().nullable(),
      }),
      resolve({ input }) {
        const { cursor } = input;

        return trpc.subscriptionPullFactory<OutputWithCursor<Post[]>>({
          intervalMs: 1000,
          pull(emit) {
            const posts = await getPostsFromDb();
            const newCursor = hash(posts);
            if (newCursor !== cursor) {
              emit.data({ data: posts, cursor: newCursor });
            }
          },
        });
      },
    });	    
  });

Client

  function MyComponent() {
    const postsQuery = hooks.useLiveQuery(['postsLive', {}]);

    return <pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>;
  }

@vercel
Copy link

vercel bot commented Feb 11, 2021

This pull request is being automatically deployed with Vercel (learn more).
To see the status of your deployments, click below or on the icon next to each commit.

chat – ./examples/next-ssg-chat

🔍 Inspect: https://vercel.com/trpc/chat/rkl75idl1/tmp.trpc.io
✅ Preview: https://chat-git-feature-live-query.tmp.trpc.io

hello-world – ./examples/next-hello-world

🔍 Inspect: https://vercel.com/trpc/hello-world/c84xhbax3/tmp.trpc.io
✅ Preview: https://hello-world-git-feature-live-query.tmp.trpc.io

@KATT KATT changed the title [RFC] useLiveQuery useLiveQuery Feb 11, 2021
@KATT KATT marked this pull request as ready for review February 11, 2021 16:07
@KATT KATT changed the title useLiveQuery useLiveQuery() Feb 11, 2021
@KATT KATT merged commit e5e809c into main Feb 11, 2021
@KATT KATT deleted the feature/live-query branch February 11, 2021 16:16
KATT added a commit that referenced this pull request Feb 19, 2021
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 14, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant