Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active February 12, 2020 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/66cb169aed6573628dbe2723b8f79084 to your computer and use it in GitHub Desktop.
Save ryanflorence/66cb169aed6573628dbe2723b8f79084 to your computer and use it in GitHub Desktop.
function PokemonInput({ defaultValue, onChange }) {
const [pokémon, setPokémon] = useState("pikachu")
const [img, setImg] = useState()
const [error, setError] = useState(null)
useEffect(() => {
let isCurrent = true
fetch(`https://pokeapi.co/api/v2/pokemon/${pokémon}/`)
.then(res => res.json())
.then(res => {
if (isCurrent) {
let name = res.name.replace(/^\w/, c => c.toUpperCase())
let sprite = res.sprites.front_default
onChange({ name, sprite })
setPokémon(name) // capitalizing name
setImg(sprite)
}
})
.catch(error => {
setError(error)
})
return () => {
isCurrent = false
}
}, [pokémon])
return (
<input
onChange={e => setPokémon(e.target.value)}
defaultValue={defaultValue}
type="text"
style={{ borderColor: error ? "red" : "" }}
/>
)
}
function useTitle(title) {
useEffect(() => {
document.title = title
}, [title])
}
////////////////////////////////////////////////////////////////////////////////
function Pokemon() {
const [pokémon, setPokémon] = useState({ name: "Pikachu", sprite: null })
useTitle("Saying hello to " + pokémon.name)
return (
<div>
<PokemonInput
onChange={fetchedPokemon => setPokémon(fetchedPokemon)}
defaultValue={pokémon.name}
type="text"
/>
Hello, {pokémon.name}! {pokémon.sprite && <img src={pokémon.sprite} />}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment