Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created August 14, 2026 11:21
Show Gist options
  • Select an option

  • Save lejonmanen/d1e589fa68fef0c235b591333e2b4480 to your computer and use it in GitHub Desktop.

Select an option

Save lejonmanen/d1e589fa68fef0c235b591333e2b4480 to your computer and use it in GitHub Desktop.
TypeScript API states
type ApiState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; pokemonList: string[] }
| { status: "error"; error: string };
const [state, setState] = useState<ApiState>({ status: "idle" });
async function fetchPokemon() {
setState({ status: "loading" });
try {
const res = await fetch("https://pokeapi.co/api/v2/pokemon");
const json = await res.json();
setState({ status: "success", pokemonList: json.results.map((p: any) => p.name) });
} catch (e) {
setState({ status: "error", error: "Kunde inte hämta data" });
}
}
// Rendering:
if (state.status === "idle") return <button onClick={fetchPokemon}>Hämta</button>;
if (state.status === "loading") return <p>Laddar...</p>;
if (state.status === "error") return <p>Fel: {state.error}</p>;
return <ul>{state.pokemonList.map(p => <li key={p}>{p}</li>)}</ul>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment