Last active
July 18, 2019 19:25
-
-
Save gabrielleme00/394e9ac5f81d2d47965e0ef7e2edc303 to your computer and use it in GitHub Desktop.
Exemplo de requisição com fetch() em React | API Star Wars
This file contains 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
import React from 'react'; | |
import './App.css'; | |
class Person extends React.Component { | |
// Define os estados | |
constructor(props) { | |
super(props); | |
this.state = { | |
error: null, | |
isLoaded: false, | |
id: this.props.id, | |
person: {} | |
} | |
} | |
// Quando este componente for inserido no DOM | |
componentDidMount() { | |
// Requisitar a pessoa do ID recebido | |
fetch("https://swapi.co/api/people/" + this.state.id) | |
// Ao terminar, passar o resultado para JSON | |
.then(res => res.json()) | |
// Ao terminar, definir o resultado como objeto (e o erro, se tiver) | |
.then( | |
result => { | |
this.setState({ | |
isLoaded: true, | |
person: result | |
}) | |
}, | |
error => { | |
this.setState({ | |
isLoaded: true, | |
error | |
}) | |
} | |
) | |
} | |
render() { | |
const {error, isLoaded, person} = this.state; | |
let message = ""; | |
if (error) { | |
// Se houver algum erro | |
message = <div>Erro na requisição: {error.message}</div> | |
} else if (!isLoaded) { | |
// Se não ocorreram erros mas ainda não carregou | |
message = <div>Carregando...</div> | |
} else { | |
// Se deu tudo certo :D | |
message = <div>{person.name}</div> | |
} | |
return message; | |
} | |
} | |
export default class App extends React.Component { | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<Person id="1"/> | |
</header> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment