Skip to content

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.

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.

import { createPromiseMachine } from "matchina";
// Function to create a promise machine for fetching data
export 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();
});
}

The fetcher follows the standard promise machine lifecycle:

  1. Idle - Ready to make a request
  2. Pending - Request is in flight, shows loading state
  3. Resolved - Request succeeded, displays the response data
  4. 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.

Now that you’ve seen a basic promise machine, you might want to explore: