LearningPad API Client Example

This is a comprehensive example demonstrating the usage of @learningpad/api-client with JSONPlaceholder API for CRUD operations on posts and comments.

Features Demonstrated:

  • Query hooks for data fetching with caching and error handling
  • Mutation hooks for CRUD operations with optimistic updates
  • Real-time data synchronization
  • Form management for different operations
  • Proper error handling and loading states
  • Automatic cache invalidation
  • Success/error notifications

API Client Integration Guide

Step 1: Install @learningpad/api-client

npm install @learningpad/api-client @tanstack/react-query

Step 2: Query Provider Configuration

Configure the Query Provider with the API client:

// components/providers/query-provider.tsx "use client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import React from "react"; const QueryProvider = ({ children }: { children: React.ReactNode }) => { const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 1000 * 60 * 2, // 2 minutes gcTime: 1000 * 60 * 10, // 10 minutes }, }, }); return ( <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> ); }; export default QueryProvider;

Step 3: API Configuration

Configure the API client with multiple services:

// api/config.ts import { ApiClientOptions, ApiConfig, ApiService } from "@learningpad/api-client"; const apiConfig: ApiClientOptions = { services: { posts: { name: "posts", baseURL: "https://jsonplaceholder.typicode.com/posts", timeout: 10000, }, comments: { name: "comments", baseURL: "https://jsonplaceholder.typicode.com/comments", timeout: 10000, }, // ... other services }, defaultTimeout: 10000, defaultHeaders: { "Content-Type": "application/json", }, }; ApiConfig.initialize(apiConfig); // Export service instances export const postService = new ApiService("posts"); export const commentService = new ApiService("comments");

Step 4: App Layout Setup

Configure the app layout to include the Query Provider:

// app/layout.tsx import QueryProvider from "@/components/providers/query-provider"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <QueryProvider> <main>{children}</main> </QueryProvider> </body> </html> ); }

Step 5: Create Custom Hooks

Create hooks using the API service instances for all CRUD operations:

// api/hooks/usePosts.ts import { postService } from "../config"; // Read: Fetch all posts export const usePosts = () => { return postService.useQuery<Post[]>({ key: ["posts"], url: "", }); }; // Read: Fetch a single post export const usePost = (id: string) => { return postService.useQuery<Post>({ key: ["post", id], url: `/${id}`, }); }; // Create: Create a new post export const useCreatePost = () => { return postService.useMutation<Post, CreatePost>({ keyToInvalidate: { queryKey: ["posts"] }, url: "", method: "post", successMessage: "Post created successfully!", errorMessage: "Failed to create post", }); }; // Update: Update an existing post export const useUpdatePost = (id: string) => { return postService.useMutation<Post, Partial<CreatePost>>({ keyToInvalidate: { queryKey: ["posts"] }, url: `/${id}`, method: "put", successMessage: "Post updated successfully!", errorMessage: "Failed to update post", }); }; // Delete: Delete a post export const useDeletePost = (id: string) => { return postService.useMutation<void, void>({ keyToInvalidate: { queryKey: ["posts"] }, url: `/${id}`, method: "delete", successMessage: "Post deleted successfully!", errorMessage: "Failed to delete post", }); };

Step 6: Use Hooks in Components

Example of how to use all CRUD hooks in a UI component:

// app/posts/_components/PostCard.tsx "use client"; import { useDeletePost, useUpdatePost, usePosts, usePost } from "@/api/hooks/usePosts"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; export function PostCard({ post }: { post: Post }) { // Read Operations: Fetch data // In parent component or here for list of posts // const { data: posts, isLoading, error } = usePosts(); // Fetch single post details // const { data: postDetails } = usePost(post.id.toString()); // Update: useUpdatePost hook const { mutateAsync: updatePost, isPending: isUpdating } = useUpdatePost( post.id.toString() ); // Delete: useDeletePost hook const { mutateAsync: deletePost, isPending: isDeletingPost } = useDeletePost( post.id.toString() ); const handleUpdate = async () => { try { await updatePost({ title: "Updated Title", body: "Updated body content", userId: 1, }); } catch (error) { console.error("Failed to update post:", error); } }; const handleDelete = async () => { try { await deletePost(); } catch (error) { console.error("Failed to delete post:", error); } }; return ( <Card className="hover:shadow-lg transition-all duration-200"> <CardHeader> <CardTitle className="text-lg font-semibold"> {post.title} </CardTitle> </CardHeader> <CardContent> <p className="text-muted-foreground text-sm"> {post.body} </p> </CardContent> <CardFooter className="gap-2"> <Button variant="outline" size="sm" onClick={handleUpdate} disabled={isUpdating} > {isUpdating ? "Updating..." : "Update"} </Button> <Button variant="destructive" size="sm" onClick={handleDelete} disabled={isDeletingPost} > {isDeletingPost ? "Deleting..." : "Delete"} </Button> </CardFooter> </Card> ); } // Example: Creating a new post (can be in a separate form component) // function CreatePostForm() { // const { mutateAsync: createPost, isPending: isCreating } = useCreatePost(); // // const handleCreate = async () => { // try { // await createPost({ // title: "New Post", // body: "Post content", // userId: 1 // }); // } catch (error) { // console.error("Failed to create post:", error); // } // }; // // return <Button onClick={handleCreate} disabled={isCreating}> // {isCreating ? "Creating..." : "Create Post"} // </Button>; // }

Key Features

  • • Complete CRUD Operations: Full support for Create, Read, Update, and Delete operations with custom hooks
  • • Multiple Services: Configure different API endpoints for posts, users, comments, etc.
  • • Token Management: Automatic JWT token handling with refresh logic
  • • Notifications: Built-in toast notifications for success/error states
  • • React Query Integration: Automatic caching, background updates, and error handling
  • • TypeScript Support: Full type safety with TypeScript interfaces
  • • Cache Invalidation: Automatic cache updates after mutations
  • • Loading & Error States: Built-in handling for pending states and error scenarios