Promise Fetcher
A simple HTTP fetcher built with promise machines, demonstrating how to handle asynchronous operations with automatic state management for loading, success, and error states.
Implementation Details
Section titled “Implementation Details”This example demonstrates the core promise machine pattern for HTTP requests:
- Automatic state management - Promise machines handle Idle, Pending, Resolved, and Rejected states
- Type-safe parameters - URL and options are passed as typed parameters
- Error handling - HTTP errors and network failures are automatically caught
- Reset functionality - Machine can be reset by recreating the instance
- Layout-aware UI - Results display with proper overflow handling
The promise machine automatically transitions between states based on the fetch operation lifecycle, providing a clean abstraction over async operations.
Source Code
Section titled “Source Code”import { createPromiseMachine } from "matchina";
// Function to create a promise machine for fetching dataexport function createPromiseFetcherMachine() { return createPromiseMachine(async (url: string, options?: RequestInit) => { const response = await fetch(url, options); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return response.json(); });}
import { useMachine } from "matchina/react";import { useMemo, useState, useCallback } from "react";import { createPromiseFetcherMachine } from "./machine";
export function usePromiseFetcher() { const [machineId, setMachineId] = useState(0);
const fetcher = useMemo(() => createPromiseFetcherMachine(), [machineId]); useMachine(fetcher);
const reset = useCallback(() => { setMachineId((id) => id + 1); }, []);
return { machine: fetcher, reset };}
import { useState } from "react";
interface PromiseFetcherViewProps { machine: any; onReset?: () => void;}
export function PromiseFetcherView({ machine, onReset,}: PromiseFetcherViewProps) { const [url, setUrl] = useState("https://httpbin.org/delay/1"); const state = machine.getState(); const isIdle = state.is("Idle");
const handleFetch = () => { machine.execute(url); };
const handleReset = () => { onReset?.(); };
return ( <div className="space-y-4 p-4 border rounded-lg max-w-full"> <div className="space-y-2"> <div className="flex gap-2 items-center"> <input type="text" value={url} onChange={(e) => setUrl(e.target.value)} className="flex-1 px-2 py-1 border rounded min-w-0" placeholder="Enter URL to fetch" disabled={!isIdle} /> <button onClick={handleFetch} disabled={!isIdle} className="px-4 py-1 bg-blue-500 text-white rounded disabled:opacity-50 whitespace-nowrap" > Fetch </button> {!isIdle && ( <button onClick={handleReset} className="px-4 py-1 bg-gray-500 text-white rounded whitespace-nowrap" > Reset </button> )} </div> </div>
<div className="p-3 rounded bg-gray-100 dark:bg-gray-800 max-w-full overflow-hidden"> {state.match({ Idle: () => <span>Ready to fetch data</span>, Pending: ({ params }: any) => ( <span>Fetching from {params[0]}...</span> ), Resolved: () => <div className="text-green-600">Success!</div>, Rejected: (error: any) => ( <span className="text-red-600">Error: {error.message}</span> ), })} </div> </div> );}
import { PromiseFetcherView } from "./PromiseFetcherView";import { usePromiseFetcher } from "./hooks";
export function PromiseFetcher() { const { machine, reset } = usePromiseFetcher(); return <PromiseFetcherView machine={machine} onReset={reset} />;}
How It Works
Section titled “How It Works”The fetcher follows the standard promise machine lifecycle:
- Idle - Ready to make a request
- Pending - Request is in flight, shows loading state
- Resolved - Request succeeded, displays the response data
- Rejected - Request failed, shows error message
The reset functionality recreates the machine instance by incrementing a machineId
, which forces React to create a fresh machine that starts in the Idle state.
Next Steps
Section titled “Next Steps”Now that you’ve seen a basic promise machine, you might want to explore:
- Advanced Fetcher - Retry logic, timeouts, and abort functionality
- Async Calculator - Promise machines for computations
- Promise Machine Guide - Complete promise machine documentation