【React Native入門】7-3 データアクセス

「React Native入門　掌田 津耶乃著」にて動作確認したコードを逐一まとめた記事です。
基本は自分用のメモですので、動作確認したい場合ご利用ください。
ある程度は1記事を更新していき、セッションが切り替わったら別記事に残していこうと思います。

目次
[ P.318〜P.323 ] ネットワークアクセス・テキストデータを取得する
[ P.323〜P.324 ] JSONデータを取得する
[ P.329〜P.334 ] AsyncStorageデータベース

---

[ P.318〜P.323 ] ネットワークアクセス・テキストデータを取得する

Fetch API

```js
fetch('指定アドレス',
{
 method: 'GET',
 headers: {
  // ヘッダー情報
 },
}).then((response) => {
  // 処理
 });
});
```

```js:App.js
import React, { Component } from 'react';
import { StyleSheet, View, ScrollView, Text, TextInput, Button ,Alert } from 'react-native';
import { Header } from 'react-native-elements';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.input = '';
    this.state = {
      text: 'fetch data...',
    };
  }

  doType = (text) => this.input = text;

  doAction = () => {
    let id = this.input == '' ? '1' : this.input;
    fetch('https://jsonplaceholder.typicode.com/users/' + id,
    {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    }).then((response) => {
      response.text().then((txt) => {
        this.setState({ text:txt });
      });
    });
  }

  render() {
    return (
      <View style={styles.base}>
        <Header
          leftComponent={{
            icon: 'menu', 
            color: 'white', 
            size: 25,
            onPress: this.doActionLeft
          }}
          centerComponent={{
            text: 'Sample App',
            style: styles.header
          }}
          rightComponent={{
            icon: 'android',
            color: 'white',
            size: 25,
            onPress: this.doActionRight
          }}
          otherContainerStyles={{
            height: 100,
            backgroundColor: '#dd0000'
          }}
          innerContainerStyles={{
            height: 100,
            backgroundColor: '#dd0000'
          }}
        />

        <View style={styles.body}>
          <ScrollView style={{ flex: 1 }}>
            <Text style={ styles.message }>
              { this.state.text }
            </Text>
          </ScrollView>
          <TextInput
            style={ styles.input }
            placeholder='type id number:'
            onChangeText={ this.doType }
          />
          <Button title="Click" onPress={ this.doAction } />
        </View>
      </View>
    );
  }
  doActionLeft = () => { Alert.alert('Left icon tapped!'); }
  doActionRight = () => { Alert.alert('Right icon tapped!'); }
}

const styles = StyleSheet.create ({
  base: {
    padding: 0,
    flex: 1,
    backgroundColor: '#ddd',
  },
  body: {
    padding: 10,
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    color: '#fff',
    fontSize: 28,
    fontWeight: '100',
  },
  message: {
    paddingTop: 10,
    fontSize: 14,
  },
  input: {
    margin: 10,
    fontSize: 24,
  }
});
```

---

[ P.323〜P.324 ] JSONデータを取得する

```js:App.js
// ...

fetch('https://jsonplaceholder.typicode.com/users/' + id,
{
 method: 'GET',
 headers: {
  Accept: 'application/json',
  'Content-Type': 'application/json',
 },
}).then((response) => {
  response.json().then((json) => {
  this.setState({ text:json.name + '\n' + json.email + '\n' + json.phone});
 });
});

// ...
```

---

[ P.329〜P.334 ] AsyncStorageデータベース

```js:App.js
import React, { Component } from 'react';
import { StyleSheet, View, ScrollView, Alert, AsyncStorage, Text, TextInput, Button } from 'react-native';
import { Header } from 'react-native-elements';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 'database access...',
      id: '',
      name: '',
      mail: '',
    };
  }

  doId = (text) => this.setState({ id:text });
  doName = (text) => this.setState({ name:text });
  doMail = (text) => this.setState({ mail:text });

  doPut = async() => {
    try {
      let count = await AsyncStorage.getItem('MyData_count');
      if(count == null) { count = 1; }
      let data = {
        name: this.state.name,
        mail: this.state.mail
      };
      await AsyncStorage.setItem('MyData_' + count, JSON.stringify(data));
      await AsyncStorage.setItem('MyData_count', '' + (count + 1));
      this.setState({
        id: '',
        name: '',
        mail: '',
      });
      Alert.alert('put data');
    } catch (error) {
      console.log(error);
      Alert.alert(error);
    }
  }

  doGet = () => {
    try {
      AsyncStorage.getItem('MyData_' + this.state.id)
      .then((data) => {
        if(data !== null) {
          let obj = JSON.parse(data);
          this.setState({
            name: obj.name,
            mail: obj.mail,
          });
        } else {
          Alert.alert('no data');    
        }
      });
    } catch (error) {
      console.log(error);
      Alert.alert(error);
    }
  }

  render() {
    return (
      <View style={styles.base}>
        <Header
          leftComponent={{
            icon: 'menu', 
            color: 'white', 
            size: 25,
            onPress: this.doActionLeft
          }}
          centerComponent={{
            text: 'Sample App',
            style: styles.header
          }}
          rightComponent={{
            icon: 'android',
            color: 'white',
            size: 25,
            onPress: this.doActionRight
          }}
          otherContainerStyles={{
            height: 100,
            backgroundColor: '#dd0000'
          }}
          innerContainerStyles={{
            height: 100,
            backgroundColor: '#dd0000'
          }}
        />

        <View style={styles.body}>
          <Text style={ styles.message }>
            { this.state.text }
          </Text>
          <View style={{ flex: 4 }}>
            <TextInput
              style={ styles.input }
              placeholder='ID:'
              value={ this.state.id }
              onChangeText={ this.doId }
            />
            <TextInput
              style={ styles.input }
              placeholder='NAME:'
              value={ this.state.name }
              onChangeText={ this.doName }
            />
            <TextInput
              style={ styles.input }
              placeholder='MAIL:'
              value={ this.state.mail }
              onChangeText={ this.doMail }
            />
            <Button title="PUT DATA" onPress={ this.doPut } />
            <View style={{ padding:10 }} />
            <Button title="GET DATA" onPress={ this.doGet } />
          </View>
        </View>
      </View>
    );
  }
  doActionLeft = () => { Alert.alert('Left icon tapped!'); }
  doActionRight = () => { Alert.alert('Right icon tapped!'); }
}

const styles = StyleSheet.create ({
  base: {
    padding: 0,
    flex: 1,
    backgroundColor: '#ddd',
  },
  body: {
    padding: 10,
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    color: '#fff',
    fontSize: 28,
    fontWeight: '100',
  },
  message: {
    paddingTop: 10,
    fontSize: 14,
  },
  input: {
    margin: 10,
    fontSize: 24,
  }
});
```