React Lifecycle methods diagram
Walkthrough a code sample for using State
These are some common patterns where state
used in a typical RN application.
const apiKey = 'AIzaSyAl_gQqNibe6FCE_MRBUyOOsQgmZJZvAjU';
const searchQuery = 'Codebase Edinburgh';
const url = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=${searchQuery}&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=${apiKey}`
componentDidMount() {
fetch(url).then(response => response.json())
.then((data) => {
this.setState({ placeInfo: data })
})
}
or using async/await
async componentDidMount() {
const response = await fetch(url)
const data = await response.json()
this.setState({placeInfo: data})
}
constructor(props) {
super(props);
this.state = {searchQuery: ''};
}
render() {
return (<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(searchQuery) => this.setState({searchQuery})}
/>)
}
RN Wisdom: Controversial, but ... use local state (if that's all you need - in a form for example) even if you're using a state management solution like Redux.