Day 13: Gotta fetch 'em all
Today, we start with a new component!
🎊 🎉 🎊 🎉
Pokemon
Take a stab at writing this component in a new sandbox before reading the next section.
- Name the component
Pokemon
- Make sure it’s a component that can hold
state
- Use
{ character: null }
as the initial state - Take an
id
prop. It’ll be the index of the Pokemon we fetch. - Render conditionally:
- If
state
has acharacter
, renderthis.state.character.name
- Otherwise render the message
...loading
- If
(At this point, it should always render ...loading
)
Fetch a Pokemon
You got it? Great!
In the workspace below, I’ve included a fetchPokemon
function. We’ll use it in
the next section.
Meet componentDidMount
componentDidMount
is a special power our component has. Speaking
technically, it’s a method on our component class.
When defined, it’s called when a Pokemon
is mounted into the DOM.
componentDidMount() {
fetchPokemon(1, (character) => this.setState({ character: character }))
}
componentDidMount
is the
ideal place to fetch data from a server.
Tinker with it
Use the workspace below and explore fetching data in componentDidMount
:
- Fetch a pokemon with a different id
- Log messages from
componentDidMount
andrender
observe the order in the console.