Skip to content

Latest commit

 

History

History
62 lines (47 loc) · 2.05 KB

File metadata and controls

62 lines (47 loc) · 2.05 KB

Chapter 5 - State and Lifecycle Methods

Lifecycle methods

React Lifecycle methods diagram

Walkthrough a code sample for using State

Common Patterns

These are some common patterns where state used in a typical RN application.

Fetching Data through AJAX

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})
}

Google Api Response Sample

Get a Google Api Key

Keeping track of form values

  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.

Resources