0.0.23 • Published 2 years ago

@nanorpc/client v0.0.23

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years 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

2 years ago

0.0.22

2 years ago

0.0.23

2 years ago

0.0.20

2 years ago

0.0.19

2 years ago

0.0.18

2 years ago

0.0.17

2 years ago

0.0.16

2 years ago

0.0.15

2 years ago

0.0.14

2 years ago

0.0.13

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago