Skip to content

Instantly share code, notes, and snippets.

@ulisesantana
Last active September 22, 2019 17:24
Show Gist options
  • Save ulisesantana/48e9d17df03afd4d1d5e8dc0c952596e to your computer and use it in GitHub Desktop.
Save ulisesantana/48e9d17df03afd4d1d5e8dc0c952596e to your computer and use it in GitHub Desktop.
A "Pokedex" hook for using the PokeAPI to show a list of pokemons with pagination.
import {EffectCallback, MouseEventHandler, useEffect, useState} from "react";
export interface Pokemon {
name: string,
url: string,
id: string,
img: string
}
export interface Pokedex {
nextPageHandler: MouseEventHandler,
content: Pokemon[],
prevPageHandler: MouseEventHandler
}
const noop = () => {};
const initialPokedex = {
nextPageHandler: noop,
content: [] as Pokemon[],
prevPageHandler: noop
} as Pokedex;
export function usePokedex(url = "https://pokeapi.co/api/v2/pokemon"): Pokedex {
const [pokedex, setPokedex] = useState(initialPokedex);
useEffect(updatePageGenerator(url, setPokedex) as EffectCallback, []);
return pokedex
}
const updatePageGenerator = (url: string | null, cb: Function): MouseEventHandler | null => {
if (!!url) {
return () => {
fetch(url)
.then(r => r.json())
.then(r => {
cb({
nextPageHandler: updatePageGenerator(r.next, cb),
content: r.results.map(parsePokemons),
prevPageHandler: updatePageGenerator(r.previous, cb)
});
}).catch(e => {
console.error('Error getting page', e.toString());
})
};
} else {
return null;
}
};
const parsePokemons = ({name, url}: { name: string, url: string }) => {
const [, id] = url.split('/').reverse();
return {
name: capitalize(name),
url,
id,
img: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`
}
};
const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment