Getting Started

Gettings Started

Installation

Make sure to install @trpc-swr/client along with the peer dependencies swr and @trpc/client and @trpc/server:

pnpm add @trpc-swr/client swr @trpc/client @trpc/server 

Usage

Setup tRPC hooks

In your utils/trpc.ts file:

import { createSWRProxyHooks } from "@trpc-swr/client";
import type { AppRouter } from "server/trpc";
 
export const api = createSWRProxyHooks<AppRouter>({
  links: [
    httpBatchLink({
      url: "https://localhost:3000/api/trpc",
    }),
  ],
});

In your App component:

const App = ({ Component, pageProps }: AppProps) => {
  const [client] = useState(() => api.createClient());
  return (
    <api.Provider client={client}>
      <Component {...pageProps} />
    </api.Provider>
  );
};

Use tRPC hooks

Using useSWR;

import { trpc } from "utils/trpc";
 
trpc.user.byId.preload({ id: 1 }); // Preload data for faster initial load
 
export default function Page() {
  const { data, error, isLoading } = trpc.user.byId.useSWR({ id: 1 });
 
  if (error) {
    return <div>error</div>;
  }
 
  if (!isLoading) {
    return <div>loading...</div>;
  }
 
  return <div>{data.name}</div>;
}

Using useSWRMutation

Leverage the power of useSWRMutation to create a fully typesafe mutation.

export default function Page() {
  const { trigger, data, error, isMutating, reset } =
    trpc.user.create.useSWRMutation();
 
  const handleSubmit = async (e) => {
    e.preventDefault();
    await trigger({
      name: "John Doe",
    });
  };
 
  if (isMutating) {
    return <div>loading...</div>;
  }
 
  if (error) {
    return (
      <div>
        {error.message}
        <button onClick={reset}>Try again</button>
      </div>
    );
  }
 
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Create user</button>
    </form>
  );
}