@tealup/nextjs-kit-client
v0.1.0
Published
Client-side utilities and components for Next.js applications in the TealUp SDK
Maintainers
Readme
@tealup/nextjs-kit-client
Client-side utilities and components for Next.js applications in the TealUp SDK.
Installation
npm install @tealup/nextjs-kit-client
# or
yarn add @tealup/nextjs-kit-client
# or
pnpm add @tealup/nextjs-kit-clientFeatures
- 🚀 CRUD Operations: Pre-built hooks and utilities for Create, Read, Update, Delete operations
- 🎨 UI Components: Common components for dashboards and admin interfaces
- 🔧 Form Management: Advanced form handling with validation
- 📊 Data Tables: Flexible table components with sorting, filtering, and pagination
- 🌐 API Client: Type-safe HTTP client with authentication
- 🎯 TypeScript: Full TypeScript support with comprehensive type definitions
- 📱 Responsive: Mobile-first responsive components
- 🌍 i18n Ready: Internationalization support
Quick Start
1. Configuration
// app/layout.tsx or _app.tsx
import { configureClient } from '@tealup/nextjs-kit-client';
configureClient({
apiUrl: process.env.NEXT_PUBLIC_API_URL || '/api',
locale: 'en', // or 'fa'
defaultPageSize: 10,
auth: {
tokenKey: 'auth_token',
autoRefresh: true,
},
});2. Basic CRUD Usage
// hooks/useUsers.ts
import { useCrud, BaseRepository } from '@tealup/nextjs-kit-client';
interface User {
id: number;
name: string;
email: string;
}
class UserRepository extends BaseRepository<User> {
constructor() {
super('/users');
}
}
const userRepo = new UserRepository();
export function useUsers() {
return useCrud<User>(userRepo);
}// components/UsersList.tsx
import { useUsers } from '../hooks/useUsers';
export function UsersList() {
const { data, loading, error, getAll } = useUsers();
useEffect(() => {
getAll({ page: 1, limit: 10 });
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
{data.map(user => (
<div key={user.id}>{user.name} - {user.email}</div>
))}
</div>
);
}3. Using Wrapper Components
// pages/users/index.tsx
import { IndexWrapper } from '@tealup/nextjs-kit-client/wrappers';
import { userRepo } from '../repositories/userRepo';
const columns = [
{ name: 'id', label: 'ID', field: 'id' },
{ name: 'name', label: 'Name', field: 'name' },
{ name: 'email', label: 'Email', field: 'email' },
];
export default function UsersPage() {
return (
<IndexWrapper
columns={columns}
repo={userRepo}
createUrl="/users/create"
title="Users Management"
/>
);
}API Reference
Hooks
useCrud<T>(repository: BaseRepository<T>)
Main hook for CRUD operations.
const {
// Data
data,
loading,
error,
success,
// Operations
getAll,
getById,
create,
update,
remove,
// State management
setError,
setSuccess,
} = useCrud<User>(userRepository);useApi<T>(options?)
Generic API hook for custom requests.
const { data, loading, error, execute } = useApi<User[]>({
onSuccess: (data) => console.log('Success:', data),
onError: (error) => console.error('Error:', error),
});
// Usage
await execute(() => fetch('/api/users').then(res => res.json()));useAuth()
Authentication management hook.
const {
user,
token,
isAuthenticated,
login,
logout,
refreshToken,
} = useAuth();Components
Wrapper Components
IndexWrapper- Complete index page with table, search, filtersCreateWrapper- Form wrapper for creating entitiesUpdateWrapper- Form wrapper for updating entitiesDetailWrapper- Detail view with actionsLayoutWrapper- Complete layout with drawer, toolbar, bottom bar
Common Components
Loading- Loading spinnerNotFound- 404 page componentStatusBadge- Status indicatorDateDisplay- Formatted date displayConfirmDialog- Confirmation modal
Utilities
FormHelper
Form validation and transformation utilities.
import { FormHelper } from '@tealup/nextjs-kit-client/utils';
// Validate form data
const result = FormHelper.validate(schema, formData);
// Format date for input
const dateString = FormHelper.formatDateForInput(new Date());
// Parse number safely
const number = FormHelper.parseNumber('123', 0);DateHelper
Date formatting and manipulation.
import { DateHelper } from '@tealup/nextjs-kit-client/utils';
// Format date
const formatted = DateHelper.format(new Date(), 'yyyy/MM/dd', 'fa');
// Relative time
const relative = DateHelper.getRelativeTime(date, 'en');
// Check if today
const isToday = DateHelper.isToday(date);StorageHelper
Local/session storage with SSR support.
import { StorageHelper } from '@tealup/nextjs-kit-client/utils';
// Local storage
StorageHelper.setLocal('key', { data: 'value' });
const data = StorageHelper.getLocal('key', defaultValue);
// Session storage
StorageHelper.setSession('key', value);
const sessionData = StorageHelper.getSession('key');HTTP Client
BaseRepository<T>
Base class for API repositories.
class UserRepository extends BaseRepository<User> {
constructor() {
super('/users'); // API endpoint
}
// Custom methods
async getActiveUsers() {
return this.get('/users/active');
}
}ApiClient
Singleton API client with authentication.
import { ApiClient } from '@tealup/nextjs-kit-client/http';
const client = ApiClient.getInstance();
client.setAuthToken(token);
// Make authenticated requests
const data = await client.authenticatedRequest('GET', '/protected-endpoint');Configuration Options
interface ClientConfig {
apiUrl: string; // Base API URL
defaultPageSize: number; // Default pagination size
timeout: number; // Request timeout
locale: 'en' | 'fa'; // Default locale
debug: boolean; // Debug mode
auth: {
tokenKey: string; // Storage key for auth token
autoRefresh: boolean; // Auto refresh tokens
refreshThreshold: number; // Refresh threshold in minutes
};
form: {
mode: 'onChange' | 'onBlur' | 'onSubmit'; // Validation mode
showInlineErrors: boolean; // Show inline validation errors
};
table: {
pageSizeOptions: number[]; // Available page sizes
defaultViewMode: 'table' | 'card' | 'list'; // Default view
enableSelection: boolean; // Enable row selection
};
}TypeScript Support
The package is fully typed with comprehensive TypeScript definitions:
// Type-safe repository
interface User {
id: number;
name: string;
email: string;
createdAt: string;
}
class UserRepository extends BaseRepository<User, number> {
// Fully typed methods
}
// Type-safe hooks
const { data, create, update } = useCrud<User>(userRepo);
// Type-safe form schemas
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
});
type UserFormData = z.infer<typeof userSchema>;Examples
Complete CRUD Example
// repositories/userRepository.ts
export class UserRepository extends BaseRepository<User> {
constructor() {
super('/users');
}
}
// pages/users/index.tsx
export default function UsersIndex() {
return (
<IndexWrapper
columns={[
{ name: 'name', label: 'Name', field: 'name' },
{ name: 'email', label: 'Email', field: 'email' },
{ name: 'actions', label: 'Actions', render: (row) => (
<ActionsTable
actions={['view', 'edit', 'delete']}
row={row}
onView={`/users/${row.id}`}
onEdit={`/users/${row.id}/edit`}
onDelete={(user) => handleDelete(user)}
/>
)},
]}
repo={new UserRepository()}
createUrl="/users/create"
/>
);
}
// pages/users/create.tsx
export default function CreateUser() {
const formConfig = () => ({
fields: [
{ name: 'name', label: 'Name', type: 'text', required: true },
{ name: 'email', label: 'Email', type: 'email', required: true },
],
validation: userSchema,
});
return (
<CreateWrapper
title="Create User"
formConfig={formConfig}
repo={new UserRepository()}
/>
);
}Contributing
Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
License
MIT © TealUp
