npm package: @permi/react
Description: React SDK for Permi OAuth2 + PKCE authentication and token management
Author: Permi
Latest version: 0.0.12

# @permi/react

React SDK for Permi - OAuth2 + PKCE authentication and wallet management hooks for React applications.

## Installation

```bash
npm install @permi/react @tanstack/react-query react react-dom
# or
pnpm add @permi/react @tanstack/react-query react react-dom
# or
yarn add @permi/react @tanstack/react-query react react-dom
```

## Peer Dependencies

This package requires:

- `react` ^18.0.0
- `react-dom` ^18.0.0
- `@tanstack/react-query` ^5.0.0

## Usage

### Setup

Wrap your application with the `PermiProvider`:

```tsx
import { PermiProvider } from "@permi/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <PermiProvider
        baseUrl="https://permi.xyz"
        clientId="your-client-id"
        redirectUri="http://localhost:3000/callback"
      >
        <YourApp />
      </PermiProvider>
    </QueryClientProvider>
  );
}
```

### Authentication

Use the `useAuth` hook to handle authentication:

```tsx
import { useAuth } from "@permi/react";

function LoginButton() {
  const { isAuthenticated, isLoading, login, logout } = useAuth();

  if (isLoading) return <div>Loading...</div>;

  if (isAuthenticated) {
    return <button onClick={logout}>Logout</button>;
  }

  return <button onClick={login}>Login</button>;
}
```

### Wallet Hooks

#### Get Wallet Address

```tsx
import { useAddress } from "@permi/react";

function WalletAddress() {
  const { data: address, isLoading, error } = useAddress();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Address: {address}</div>;
}
```

#### Get Wallet Balance

```tsx
import { useBalance } from "@permi/react";

function WalletBalance() {
  const { data: balance, isLoading } = useBalance();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      Balance: {balance?.formatted} {balance?.symbol}
    </div>
  );
}
```

#### Get Viem Account

The `useAccount` hook returns a [viem](https://viem.sh) compatible account that can be used with viem clients:

```tsx
import { useAccount } from "@permi/react";
import { createWalletClient, http } from "viem";
import { mainnet } from "viem/chains";

function SendTransaction() {
  const { data: account, isLoading } = useAccount();

  const sendTransaction = async () => {
    if (!account) return;

    const walletClient = createWalletClient({
      account,
      chain: mainnet,
      transport: http(),
    });

    const hash = await walletClient.sendTransaction({
      to: "0x...",
      value: BigInt(1000000000000000000), // 1 ETH
    });
  };

  if (isLoading) return <div>Loading...</div>;

  return (
    <button onClick={sendTransaction} disabled={!account}>
      Send Transaction
    </button>
  );
}
```

## API Reference

### Components

#### `PermiProvider`

Provider component that must wrap your application.

**Props:**

- `baseUrl: string` - Permi API base URL
- `clientId: string` - Your OAuth2 client ID
- `redirectUri: string` - OAuth2 redirect URI
- `children: ReactNode` - Your application components

### Hooks

#### `useAuth()`

Authentication hook for login/logout functionality.

**Returns:**

- `isAuthenticated: boolean` - Whether user is authenticated
- `isLoading: boolean` - Whether authentication is loading
- `user: User | undefined` - Current user info
- `login: () => void` - Function to initiate login
- `logout: () => void` - Function to logout
- `getAccessToken: () => string` - Function to get current access token

#### `useAddress(queryOptions?)`

Hook to get the wallet address.

**Returns:** React Query result with wallet address as `Address`

#### `useBalance(queryOptions?)`

Hook to get the wallet balance.

**Returns:** React Query result with balance data

#### `useAccount()`

Hook to get a viem-compatible account object.

**Returns:**

- `data: Account | undefined` - Viem account object
- `isLoading: boolean` - Loading state

#### `usePermiContext()`

Access the Permi context directly.

**Returns:**

- `baseUrl: string` - API base URL
- `getAccessToken: () => string` - Function to get access token

## Advanced Usage

### Custom Query Options

All query hooks accept TanStack Query options:

```tsx
const { data: address } = useAddress({
  refetchInterval: 5000, // Refetch every 5 seconds
  staleTime: 10000, // Consider data stale after 10 seconds
});
```

### Error Handling

```tsx
const { data, error, isError } = useBalance();

if (isError) {
  console.error("Failed to fetch balance:", error);
}
```

## License

MIT