scrimba
Learning React basics
Fetching data from an API with React
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Fetching data from an API with React
by
AboutCommentsNotes
Fetching data from an API with React
by
Expand for more info
App.js
run
preview
console
import React, {Component} from 'react'

// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
// https://swapi.co/
//https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261

class App extends Component {
constructor () {
super ();
this.state = {
loading: false,
character: {}
}
}

componentDidMount () {
this.setState({loading: true})
fetch("https://swapi.co/api/people/22")
.then(response => response.json())
.then(data => {
this.setState({
character: data,
loading: false
})
})
}

render() {
console.log(this.state);
const text = this.state.loading ? 'loading...' : this.state.character.name;
return (
<div>
<p>{text}</p>
</div>
);
}
}

export default App;
Console
{loading:
false
, character:
{}
}
,
{loading:
true
, character:
{}
}
,
{loading:
false
, character:
{name:
"Boba Fett"
, height:
"183"
, mass:
"78.2"
, hair_color:
"black"
, skin_color:
"fair"
, eye_color:
"brown"
, birth_year:
"31.5BBY"
, gender:
"male"
, homeworld:
"https://swapi.co/api/planets/10/"
, films:
[
"https://swapi.co/api/films/2/"
,
"https://swapi.co/api/films/5/"
,
"https://swapi.co/api/films/3/"
]
, species:
[
"https://swapi.co/api/species/1/"
]
, vehicles:
[]
, starships:
[
"https://swapi.co/api/starships/21/"
]
, created:
"2014-12-15T12:49:32.457000Z"
, edited:
"2014-12-20T21:17:50.349000Z"
, url:
"https://swapi.co/api/people/22/"
}
}
,
/index.html
LIVE