Created
March 9, 2020 15:41
-
-
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.
This file contains hidden or 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
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