Skip to content

Instantly share code, notes, and snippets.

@santosh
Created March 9, 2020 15:41
Show Gist options
  • Save santosh/25708a10476f7a6397342dc61ff08f0f to your computer and use it in GitHub Desktop.
Save santosh/25708a10476f7a6397342dc61ff08f0f to your computer and use it in GitHub Desktop.
Fetching data from within #React component. Loading component can be added for smooth transition.
class App extends React.Component {
constructor() {
super()
this.state = {
character: {}
}
}
componentDidMount() {
this.setState({ loading: true })
fetch("https://swapi.co/api/people/1")
.then(response => response.json())
.then(data => {
this.setState({
character: data,
loading: false
})
})
}
render() {
const text = this.state.loading ? "Loading.." : this.state.character.name
return (
<div>
{text}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment