Skip to content

Instantly share code, notes, and snippets.

@alexkuttig
Last active January 30, 2018 09:28
Show Gist options
  • Save alexkuttig/89e1e228a62ec14bca6de6a67e2bc6b1 to your computer and use it in GitHub Desktop.
Save alexkuttig/89e1e228a62ec14bca6de6a67e2bc6b1 to your computer and use it in GitHub Desktop.
React Native setState with callback
const URL = 'https://api.github.com/repos/facebook/react-native'
class Stars extends Component {
state : {
stars: number
} = {
stars: 0
}
async componentDidMount() {
await this.fetchData().done();
// do something
}
async fetchData(): Promise<void> {
const response = await fetch(URL)
const json = await response.json()
const stars : number = json.stargazers_count
this.setState({stars: stars}, () => {
// do something after the stars are rendered
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
React Native has {this.state.stars} stars
</Text>
</View>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment