0.0.23 • Published 9 months ago

@nanorpc/client v0.0.23

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

@nanorpc/client

Installation

# npm
npm install @nanorpc/client

# yarn
yarn add @nanorpc/client

# pnpm
pnpm add @nanorpc/client

Basic setup

This setup imports the type of your router to get end-to-end typesafety. See @nanorpc/server to learn more.

import { createClient, withMiddleware } from "@nanorpc/client";
import { createSWRMiddleware } from "@nanorpc/client/swr";
import type { Router } from "./server";

let fetcher = async (key, options) => {
  return await fetch(key, options).then((res) => res.json());
};

// Optionally use the SWR cache middleware
// to store and retrieve data from the cache
fetcher = withMiddleware(fetcher, [createSWRMiddleware()]);

export const { query, mutate } = createClient<Router>("/api")(fetcher);

Call your remote procedure

import { isError } from "@nanorpc/client";
import { query, mutate } from "./client";

async function getPost(id: string) {
  // Get the fully typed post
  const response = await query.getPost(id);

  // If it responds with an error, log it and return undefined
  if (isError(response)) {
    console.error(response.error);
    return;
  }

  return response;
}

Example with React and swr

import { useQuery, useMutation } from "@nanorpc/client/swr";
import { query, mutate } from "./client";

const errors = {
  NOT_FOUND: "This post does not exist",
  SERVER_ERROR: "Something unexpected happened. Please try again later",
};

export default function Post({ id }: { id: string }) {
  const post = useQuery(query.posts.getPost(id));

  if (post.error === "NOT_FOUND") {
    const createPost = async () => {
      await mutate.posts.createPost({ id });
      post.update();
    };

    return <button onClick={createPost}>Create post</button>;
  }

  if (post.error) {
    return <>Error: {errors[post.error]}</>;
  }

  if (!post.data) {
    return <>Loading...</>;
  }

  return <h1>{post.data.title}</h1>;
}
0.0.21

10 months ago

0.0.22

10 months ago

0.0.23

9 months ago

0.0.20

11 months ago

0.0.19

11 months ago

0.0.18

11 months ago

0.0.17

11 months ago

0.0.16

11 months ago

0.0.15

11 months ago

0.0.14

11 months ago

0.0.13

12 months ago

0.0.12

12 months ago

0.0.11

12 months ago

0.0.10

12 months ago

0.0.9

12 months ago

0.0.8

12 months ago

0.0.7

12 months ago

0.0.6

12 months ago

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago