@cellsweb/rpc-client
v1.0.18
Published
Client SDK & React / React Native hooks for CellsWeb RPC API — universal fetch, automatic multipart form-data, and provider context
Downloads
2,656
Maintainers
Readme
@cellsweb/rpc-client
Official Client SDK & React / React Native Hooks for CellsWeb RPC API. Supports universal fetch, automatic multipart FormData object conversion, base header/body merging, and React hooks.
[!NOTE]
@cellsweb/rpc-clientis the official client-side SDK designed specifically to consume backend RPC services powered by@cellsweb/rpc-core.
📦 Installation
npm install @cellsweb/rpc-client
# or
pnpm add @cellsweb/rpc-client
# or
yarn add @cellsweb/rpc-client⚡ Quick Start
1. Direct API Request (rawRpcRequest)
Use rawRpcRequest anywhere outside of React providers — inside services, utility functions, state stores, or background scripts:
import { rawRpcRequest, RpcError } from "@cellsweb/rpc-client";
try {
const data = await rawRpcRequest<{ user: UserProfile }>({
baseUrl: "https://api.example.com",
namespace: "auth",
functionName: "profile",
headers: { authorization: "Bearer custom_auth_token" },
});
console.log("User profile:", data.user);
} catch (err) {
if (err instanceof RpcError) {
console.error("RPC Error:", err.code, err.message, err.status);
}
}2. Standalone Client Instance (createRpcClient)
Create a configured client instance with default baseUrl, default headers, and default body payload:
import { createRpcClient } from "@cellsweb/rpc-client";
export const rpc = createRpcClient({
baseUrl: "https://api.example.com",
defaultHeaders: () => ({ authorization: `Bearer ${getAuthToken()}` }),
defaultBody: { appId: "com.example.app" },
});
// Use anywhere in your app:
const result = await rpc.request<{ success: boolean }>({
namespace: "orders",
functionName: "create",
data: { items: [{ id: "p1", quantity: 2 }] },
});3. React & React Native Setup (<RpcProvider>)
Wrap your app root with <RpcProvider> to share configuration across all components:
import React from "react";
import { RpcProvider } from "@cellsweb/rpc-client/react";
export function App() {
return (
<RpcProvider
baseUrl="https://api.example.com"
defaultHeaders={() => ({ authorization: `Bearer ${getAuthToken()}` })}
defaultBody={{ appId: "com.example.app" }}
>
<MainNavigator />
</RpcProvider>
);
}4. Fetching Data with useRpcQuery
Data fetching hook with loading states, error handling, auto-refetch, and manual trigger:
import React from "react";
import { useRpcQuery } from "@cellsweb/rpc-client/react";
function ProductList() {
const { data, loading, error, refetch } = useRpcQuery<{ products: Product[] }>({
namespace: "products",
functionName: "list",
data: { category: "electronics" },
});
if (loading) return <div>Loading products…</div>;
if (error) return <div>Error loading products!</div>;
return (
<div>
<button onClick={() => refetch()}>Refresh</button>
{data?.products.map((p) => (
<div key={p.id}>{p.name}</div>
))}
</div>
);
}5. Mutations & Automatic File Uploads with useRpcMutation
Mutation hook for POST requests. Supports automatic multipart FormData auto-detection for Web (File/Blob) and React Native ({ uri, name, type }) objects!
import React, { useState } from "react";
import { useRpcMutation } from "@cellsweb/rpc-client/react";
function AvatarUploader() {
const [file, setFile] = useState<File | null>(null);
const { mutate, loading, error } = useRpcMutation({
namespace: "public",
functionName: "upload",
});
const handleUpload = async () => {
if (!file) return;
// Passing file objects automatically triggers multipart/form-data conversion!
const result = await mutate({
title: "My Profile Avatar",
file: file,
});
console.log("Upload successful:", result);
};
return (
<div>
<input type="file" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
<button onClick={handleUpload} disabled={loading}>
{loading ? "Uploading…" : "Upload Avatar"}
</button>
</div>
);
}🛠 Features
- Automatic Multipart Form-Data Conversion: Pass any JavaScript object with embedded Web
File/Blobor React Native{ uri, name, type }objects.@cellsweb/rpc-clientautomatically buildsFormDataand posts seamlessly! - Header & Body Merging: Configure
defaultHeadersanddefaultBodyglobally or dynamically per request. - Typed Error Handling: Catches server RPC error responses and throws
RpcErrorwithcode,message,status, andmeta. - Zero Overhead: Focused exclusively on clean, high-performance RPC API dispatching.
📜 API Reference
createRpcClient(config)
baseUrl: Base URL of the CellsWeb server.rpcEndpoint: Endpoint path (default"/rpc").defaultHeaders: Additional headers object or dynamic getter function.defaultBody: Default properties to merge into request payloads.timeoutMs: Request timeout in milliseconds (default30000).
rawRpcRequest(options)
baseUrl: Full base URL.namespace: RPC namespace string.functionName: RPC function name string.data: Payload object.headers: Additional headers object.multipart: Forcemultipart/form-dataencoding.
📄 License
MIT © Minhazur Rahman
