Skip to content

Commit

Permalink
chore: add subscription example with superjson
Browse files Browse the repository at this point in the history
  • Loading branch information
diegodelrieu committed Apr 22, 2024
1 parent 414257b commit 8325080
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 4 deletions.
1 change: 1 addition & 0 deletions examples/with-plasmo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"plasmo": "^0.84.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"superjson": "^2.2.1",
"zod": "^3.19.1"
},
"devDependencies": {
Expand Down
11 changes: 11 additions & 0 deletions examples/with-plasmo/src/background.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
import { initTRPC } from '@trpc/server';
import { observable } from '@trpc/server/observable';
import SuperJSON from 'superjson';
import { z } from 'zod';

import { createChromeHandler } from '../../../adapter';

const t = initTRPC.create({
isServer: false,
allowOutsideOfServer: true,
transformer: SuperJSON,
});

const appRouter = t.router({
openNewTab: t.procedure.input(z.object({ url: z.string().url() })).mutation(async ({ input }) => {
await chrome.tabs.create({ url: input.url, active: true });
}),
subscribeToAnything: t.procedure.subscription(() => {
return observable<string | undefined>((emit) => {
const interval = setInterval(() => {
emit.next(new Date().toISOString());
}, 1000);
return () => clearInterval(interval);
});
}),
});

export type AppRouter = typeof appRouter;
Expand Down
8 changes: 6 additions & 2 deletions examples/with-plasmo/src/contents/inpage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createTRPCProxyClient } from '@trpc/client';
import type { PlasmoCSConfig } from 'plasmo';
import type { FC } from 'react';
import SuperJSON from 'superjson';
import { windowLink } from 'trpc-browser/link';
import type { AppRouter } from '~background';

Expand All @@ -12,6 +13,7 @@ export const config: PlasmoCSConfig = {
};

const windowClient = createTRPCProxyClient<AppRouter>({
transformer: SuperJSON,
links: [/* 👉 */ windowLink({ window })],
});

Expand All @@ -30,8 +32,10 @@ const ExtensionInpageUi: FC = () => {
cursor: 'pointer',
}}
onClick={async () => {
await windowClient.openNewTab.mutate({
url: 'https://google.com',
await windowClient.subscribeToAnything.subscribe(undefined, {
onData(data) {
console.log('data', data);
},
});
}}
>
Expand Down
14 changes: 12 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8325080

Please sign in to comment.