Created
August 14, 2026 11:21
-
-
Save lejonmanen/d1e589fa68fef0c235b591333e2b4480 to your computer and use it in GitHub Desktop.
TypeScript API states
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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