Skip to content

ninadvyas/Api-State-Generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

API State Manager Generator

A Next.js application that automatically generates TypeScript-powered React hooks for API calls. This tool helps React developers quickly create production-ready custom hooks with proper typing, error handling, and optional features like caching and retry logic.

Features

  • πŸš€ Automatic Hook Generation - Generate complete React hooks from API responses
  • πŸ“ TypeScript Support - Full TypeScript interfaces generated from JSON responses
  • 🎯 Path Parameter Detection - Automatically detects and handles path parameters like {id}, {userId}
  • ⚑ Optional Features - Toggle caching, retry logic, and request cancellation
  • πŸ“‹ One-Click Copy - Copy generated code to clipboard instantly
  • 🎨 Clean UI - Modern, minimalist design with smooth animations
  • πŸ“± Responsive - Works seamlessly on desktop and mobile devices

Tech Stack

  • Next.js 14+ with App Router
  • TypeScript (strict mode)
  • Tailwind CSS for styling
  • React hooks for state management
  • Native fetch API (no external libraries)

Getting Started

Prerequisites

  • Node.js 18+ installed
  • npm or yarn package manager

Installation

  1. Clone or download this repository
  2. Install dependencies:
npm install
  1. Start the development server:
npm run dev
  1. Open http://localhost:3000 in your browser

How to Use

Step 1: Enter API Details

  1. API Endpoint URL - Enter your API endpoint (e.g., https://api.example.com/users/{id})
    • Use curly braces {} for path parameters
  2. Select HTTP Method - Choose GET or POST
  3. Configure Options - Toggle optional features:
    • Caching - Cache responses for 5 minutes
    • Retry Logic - Retry failed requests up to 3 times
    • Request Cancellation - Cancel pending requests on component unmount (GET only)

Step 2: Get Response Data

Choose one of two methods:

  • Fetch from API - Automatically fetch a sample response from the endpoint
  • Paste JSON Response - Manually paste a JSON response

Step 3: View & Copy Generated Code

The tool generates three code sections:

  1. Hook Code - Complete React hook implementation
  2. Types - TypeScript interfaces for your data
  3. Usage Example - Example component showing how to use the hook

Click the "Copy" button on any tab to copy the code to your clipboard.

Example

Input

  • URL: https://jsonplaceholder.typicode.com/users/1
  • Method: GET
  • Options: Retry enabled

Generated Hook

import { useState, useEffect, useCallback } from 'react';

export function useUser(userId: string) {
  const [data, setData] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchUser = useCallback(async () => {
    setLoading(true);
    setError(null);

    let lastError: Error | null = null;
    for (let attempt = 0; attempt < 3; attempt++) {
      try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const result = await response.json();
        setData(result);
        break;
      } catch (err) {
        lastError = err instanceof Error ? err : new Error('Unknown error');
        if (attempt === 2) {
          setError(lastError.message);
        }
      }
    }
    
    setLoading(false);
  }, [userId]);

  useEffect(() => {
    fetchUser();
  }, [fetchUser]);

  return { data, loading, error, refetch: fetchUser };
}

Project Structure

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ layout.tsx          # Root layout with metadata
β”‚   β”œβ”€β”€ page.tsx            # Main page component
β”‚   └── globals.css         # Global styles
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ Header.tsx          # App header
β”‚   β”œβ”€β”€ ApiInputForm.tsx    # Main input form
β”‚   β”œβ”€β”€ JsonInputModal.tsx  # Modal for pasting JSON
β”‚   β”œβ”€β”€ CodeDisplay.tsx     # Code display with tabs
β”‚   └── CopyButton.tsx      # Copy to clipboard button
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ codeGenerator.ts    # Main code generation logic
β”‚   β”œβ”€β”€ typeGenerator.ts    # TypeScript interface generation
β”‚   β”œβ”€β”€ urlParser.ts        # URL parsing and hook naming
β”‚   └── utils.ts            # Helper utilities
└── types/
    └── index.ts            # TypeScript type definitions

Code Generation Rules

Hook Naming

  • GET /users/{id} β†’ useUser
  • GET /users β†’ useUsers
  • POST /users β†’ useCreateUser

Type Generation

  • Analyzes JSON structure
  • Handles nested objects
  • Handles arrays (Type[])
  • Infers primitive types (string, number, boolean, null)
  • For POST: generates separate CreateXInput interface

Path Parameters

  • Detected from curly braces: {id}, {userId}, {postId}
  • Automatically added as function parameters
  • Type-safe with TypeScript

Building for Production

npm run build
npm start

Contributing

This is an MVP (Minimum Viable Product). Future enhancements could include:

  • Support for more HTTP methods (PUT, PATCH, DELETE)
  • Authentication handling
  • Request/response interceptors
  • More customization options
  • Export to different formats
  • Dark mode support

License

MIT License - feel free to use this project for any purpose.

Support

For issues or questions, please open an issue on the GitHub repository.


Built with ❀️ using Next.js and TypeScript

About

automatically generates TypeScript-powered React hooks for API calls.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors