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.

Promise machines automatically transition between states based on the fetch lifecycle:

  1. Idle — ready to make a request
  2. Pending — request in flight, shows loading state
  3. Resolved — request succeeded, displays response data
  4. Rejected — request failed, shows error message

The reset functionality recreates the machine instance by incrementing a machineId, forcing React to mount a fresh machine in the Idle state.

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();
});
}