Skip to content
cccskills
FreePublished on GitHub

data

Structure data fetching so server pages provide initial data to client components, while SWR refreshes it and handles mutations through an API client. The guidance covers cache keys, server and client responsibilities, and URL based organization context.

OriginalShow the original description

Use when implementing data fetching, API calls, server/client components, or SWR hooks

trycompai/comp2,058 stars(GitHub 2,058 + cccskills 0)

Run score Not tested

See how to install

Good for

  • Building pages that render with server-fetched initial data
  • Creating SWR hooks for API reads and mutations
  • Keeping cached data separate by organization
  • Separating server layouts from interactive client components

Files included (1)

  • SKILL.md3.8 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

Source Cursor rule: .cursor/rules/data.mdc. Original Cursor alwaysApply: false.

Data Fetching

Core Pattern: Server → Client → SWR

1. Server Page Fetches Data

// app/(app)/[orgId]/tasks/page.tsx
export default async function TasksPage({ params }: { params: Promise<{ orgId: string }> }) {
  const { orgId } = await params; // From URL, NOT session
  const tasks = await getTasks(orgId);
  return <TaskListClient organizationId={orgId} initialTasks={tasks} />;
}

2. Client Component Receives Initial Data

// components/TaskListClient.tsx
'use client';

export function TaskListClient({ organizationId, initialTasks }: Props) {
  const { tasks, createTask, updateTask } = useTasks({
    organizationId,
    initialData: initialTasks,
  });
  // Initial render is instant - no loading state
}

3. SWR Hook with fallbackData

// hooks/useTasks.ts
export function useTasks({ organizationId, initialData }: UseTasksOptions) {
  const { data, mutate } = useSWR(
    ['/v1/tasks', organizationId], // Include orgId for cache isolation
    async ([endpoint, orgId]) => {
      const response = await apiClient.get(endpoint, orgId);
      return response.data?.tasks ?? [];
    },
    { fallbackData: initialData }
  );

  const createTask = async (input: CreateTaskInput) => {
    await apiClient.post('/v1/tasks', input, organizationId);
    mutate(); // Revalidate
  };

  const updateTask = async ({ taskId, input }: { taskId: string; input: UpdateTaskInput }) => {
    await apiClient.put(`/v1/tasks/${taskId}`, input, organizationId);
    mutate(); // Revalidate
  };

  return { tasks: data ?? [], createTask, updateTask, mutate };
}

API Client

Use apiClient from @/lib/api-client:

import { apiClient } from '@/lib/api-client';

await apiClient.get<ResponseType>('/v1/endpoint', organizationId);
await apiClient.post<ResponseType>('/v1/endpoint', body, organizationId);
await apiClient.put<ResponseType>('/v1/endpoint', body, organizationId);
await apiClient.delete('/v1/endpoint', organizationId);

Server vs Client Components

Layouts = server. Interactive logic in separate client components.

// layout.tsx (server)
export default function Layout({ children }) {
  return (
    <PageLayout>
      <PageHeader title="Title" />
      <ClientTabs /> {/* Client component */}
      {children}
    </PageLayout>
  );
}

// components/ClientTabs.tsx
'use client';
export function ClientTabs() {
  const router = useRouter();
  // Interactive logic here
}

State Management

No nuqs - use React state or Next.js patterns:

// ✅ React state for UI
const [isOpen, setIsOpen] = useState(false);

// ✅ Next.js for URL state
const router = useRouter();
const searchParams = useSearchParams();

// ❌ No nuqs
import { useQueryState } from 'nuqs';

Rules

// ✅ Always
const { orgId } = await params;                    // From URL params
const { data } = useSWR(key, f, { fallbackData }); // With initial data
await apiClient.get('/v1/endpoint', orgId);        // Use apiClient
useSWR(['/v1/tasks', orgId], fetcher);            // Include orgId in key

// ❌ Never
const orgId = session?.activeOrganizationId;       // From session
const { data } = useSWR('/api/data');              // No initial data
await fetch('/api/endpoint');                      // Direct fetch

File Structure

app/(app)/[orgId]/tasks/
├── page.tsx                 # Server - fetches data
├── components/
│   └── TaskListClient.tsx   # Client - receives initialData
├── hooks/
│   └── useTasks.ts          # SWR hook with mutations
└── data/
    └── queries.ts           # Server-side queries

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Guide API endpoint changes so request DTOs, runtime validation, OpenAPI documentation, and MCP tool metadata stay aligned. It covers discoverability, authentication, uploads, long-running tasks, and response types that MCP tools cannot handle.

  • Adding an API endpoint with a request body
  • Updating DTO validation and OpenAPI metadata
  • Making an endpoint available as an MCP tool
trycompai/comp2.1KUpdated Oct 24, 2026

Review specified files for design system usage, replace legacy @trycompai/ui components and lucide-react icons with available @trycompai/design-system equivalents, and run the app type check to verify the migration.

  • Migrating legacy UI components
  • Replacing lucide-react icons with Carbon icons
  • Checking specified files for design system compliance
trycompai/comp2.1KUpdated Oct 24, 2026

audit-hooks

FreeSummary

Review specified files for outdated hook and API patterns, then replace them with the prescribed SWR hooks, API clients, or server API calls. The guidance covers data fetching, mutations, cache updates, and response handling, followed by a typecheck command.

  • Auditing files for disallowed API and hook patterns
  • Replacing raw fetch calls with the API client
  • Migrating server actions and database mutations to API hooks
trycompai/comp2.1KUpdated Oct 24, 2026

audit-rbac

FreeSummary

Review NestJS API endpoints and frontend components for role-based access control and audit log compliance. The skill lists permission, guard, route, and UI gating rules, then directs the agent to fix violations and run type checks.

  • Auditing API routes for permission decorators
  • Checking UI actions against user permissions
  • Fixing access control inconsistencies
trycompai/comp2.1KUpdated Oct 24, 2026

audit-tests

FreeSummary

Audit unit tests for components that use permissions. Add missing tests and fix failures, checking that administrators can use mutation controls, auditors cannot, and read-only content remains visible to both.

  • Adding permission tests for a component
  • Checking admin and auditor behavior
  • Fixing failing permission-related tests
trycompai/comp2.1KUpdated Oct 24, 2026

Set up Better Auth for TypeScript applications, including server and client configuration, database adapters, sessions, email and social sign-in, and plugins. The guide also highlights environment variables, schema generation, and security settings to review.

  • Configuring Better Auth in a TypeScript app
  • Connecting an ORM or database adapter
  • Setting up sessions and cookie storage
trycompai/comp2.1KUpdated Oct 24, 2026

See all skills by trycompai

Report a problem with this skill